'''
Created on Jun 25, 2012

@author: Admin
'''
#http://wxpython.org/docs/api/wx.KeyEvent-class.html
import ctypes
import glob
import os
import paramiko
import re
import tempfile
import time
import tkFont
import Tkinter
from Tkinter import *
import tkFileDialog
import tkMessageBox
import threading
import urllib
import win32api
import win32con
from Tkinter import *
from ctypes.wintypes import MAX_PATH
from win32com.client import GetObject
import subprocess
import socket
import zipfile
import ftplib

PROCNAME = "SSHClient.exe"
HOST = 'elisoft.co.kr'
USER = 'elisoft'
PASS = '7890'
DIRN = '/setup_eli_ssh'
FILE = 'SSHClient.zip'
VERSION_FILE = 'version.txt'
VERSION_FILE_TEMP = 'version_temp.txt'

DIRN_DES = ''
FILE_DES = 'SSHClient.zip'
APP_NAME = 'SSHClient'
UPDATE_FILE = "update.exe"
DOWNLOAD_COUNT = 0.0
fileSize = 0
global f,tk_cancel,top,label,UPDATE_APP, root, main

class UpdateApplication(threading.Thread):
    def __init__(self,ssh):
        threading.Thread.__init__(self)
        self.ssh=ssh
   
    #download file update .zip
    def downloadUpdateFile(self):
        rs = False
            
        try:
            global f
            f = ftplib.FTP(HOST)
        except (socket.error, socket.gaierror):
            print 'ERROR: cannot reach "%s"' % HOST
                
        print '*** Connected to host "%s"' % HOST

        try:
            f.login(USER, PASS)
        except ftplib.error_perm:
            print 'ERROR: cannot login anonymously'
            self.ssh.enableMenu()
            f.quit()
            #return
        print '*** Logged in as "anonymous"'

        try:
            f.cwd(DIRN)
        except ftplib.error_perm:
            print 'ERROR: cannot CD to "%s"' % DIRN
            self.ssh.enableMenu()
            f.quit()
            #return
        print '*** Changed to "%s" folder' % DIRN

        try:
            f.retrbinary('RETR %s' % VERSION_FILE,
                            open(VERSION_FILE_TEMP, 'wb').write)
                
            if self.checkVersion() == True :
                print 'update'
               
                self.openUpdate()
                
                
            else:
                print 'unupdate'
                global main
                main.enableMenu()
                        
                
        except ftplib.error_perm:
            print 'ERROR: cannot read file "%s"' % FILE
            self.ssh.enableMenu()
            os.unlink(FILE)
        else:
            print '*** Downloaded "%s" to CWD' % FILE
        f.quit()
        
        return rs
    
    
    #fileSave = open(FILE, 'wb')

    def handleDownload(self,block):
        try:
            global DOWNLOAD_COUNT    
            DOWNLOAD_COUNT += len(block)
            self.fileSave.write(block)    
            #print (str(USER_COUNT)+" / "+str(fileSize))
            #print DOWNLOAD_COUNT
            global top
            self.top = Tkinter.Toplevel(top)
            
            temp = "%d%% complete" % (round((DOWNLOAD_COUNT/fileSize)*100))
            Tkinter.Label(self.top, text="tts").grid(row=2, column=2, columnspan=6)
        
            print "%d%% complete" % (round((DOWNLOAD_COUNT/fileSize)*100))
        except Exception as inst:
            print inst
            pass
    
    #get current derectory
    def currentDer(self):
        print "currentDer: "+os.getcwd()
        return os.getcwd()

    def notNewVersion1(self):        
        self.wins = Tkinter.Toplevel()
        print 'a'
        self.wins.top=Tkinter.Toplevel(self.wins)
        Label(self.wins.top,  text='information').pack() 
        Button(self.wins.top, text='OK', command=self.quitHello).pack()
        
        self.wins.protocol('WM_DELETE_WINDOW', self.quitHello)         
             
        self.wins.grab_set()           
        self.wins.mainloop()           
        self.wins.destroy()
        print 'dialog exit'

    def quitHello(self):
        global root
        self.wins.quit()
        root.enableMenu()

   
            
    #unzip file upload .zip
    def unzipfile(self):
        currentDers = self.currentDer()
        currentDers = currentDers +'//'
        
        rs = False
        try :
            zf = zipfile.ZipFile(FILE)      
            for name in zf.namelist():
                
                if  name.endswith('/') and (name != APP_NAME):                 
                    if not os.path.exists(currentDers+name):
                        os.mkdir(currentDers+name)
                        print currentDers+name
                else:
                    try:
                        print name 
                        print 'b'
                        os.remove(os.path.join(currentDers,name))
                        print 'b'
                        outfile = open(os.path.join(currentDers,name), 'wb')
                        outfile.write(zf.read(name))

                    except Exception as inst:
                        print inst
                        pass
                                        
            rs = True
                       
        except  Exception as inst:
            print inst

        return rs
                          
    #check version
    def checkVersion(self):
        rs = False
        try:
            oldVersion = self.getCurrentVersion()
            newVersion = self.getNewVersion()
            if oldVersion < newVersion :
                rs = True
               
        except Exception as inst:
            print inst
            pass
                
        return rs

            
    #get current version by file
    def getCurrentVersion(self):
        myfile = open(VERSION_FILE, 'r')
        myVersion = myfile.readline()
        myfile.close()
        return myVersion

    #get new version by file
    def getNewVersion(self):
        myfile = open(VERSION_FILE_TEMP, 'r')
        myVersion = myfile.readline()
        myfile.close()
        return myVersion
    
    def openApp(self):
        temp = self.currentDer()+"\\"+PROCNAME
        print temp
        subprocess.call(temp)

    def killApp(self):
        WMI = GetObject('winmgmts:')
        processes = WMI.InstancesOf('Win32_Process')
        for proc in processes:
            if proc.Properties_("Name").Value == PROCNAME:
                proc.Terminate
        

    def openUpdate(self):
        temp = self.currentDer()+"\\"+UPDATE_FILE
        print "openUpdate: "+temp
        subprocess.call(temp)

    def killUpdate(self):
        WMI = GetObject('winmgmts:')
        processes = WMI.InstancesOf('Win32_Process')
        for proc in processes:
            if proc.Properties_("Name").Value == UPDATE_FILE:
                proc.Terminate

    def run(self):
        print 'run'
        try:
            self.downloadUpdateFile()
        except:
            pass

    def stop(self):
        self._running = False

    #def start(self):

    #   self.run()

    #def exit():
    #   self.exit()

class ActiveProgramByKey(threading.Thread):
    def __init__(self, key):
        threading.Thread.__init__(self)
        self.key = key

    def run(self):
        while True:
            time.sleep(0.1)

class SEND_DIRECT(threading.Thread):
    def __init__(self,ssh):
        threading.Thread.__init__(self)
        self.ssh=ssh
        
    def run(self):
        print 'sendKeyCode'
        print self.ssh.text.get('end-1c','end')+'   .'

class GO_ON(threading.Thread):
    def __init__(self,ssh, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        print '1'
        
    def run(self):
        i=0
        while i<3:
            try:
                i+=1
                print len(self.ssh.channel.in_buffer._buffer)
                #print self.ssh.channel.in_buffer.read(1024, 1)                
                self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)                
                self.ssh.text.insert('end', self.ssh.accept_host)
                break
                
            except:
                pass
            finally:
                print 'finnallysss'
        i=0
        while i<4:
            try:
                i+=1
                print len(self.ssh.channel.in_buffer._buffer)
                #print self.ssh.channel.in_buffer.read(1024, 1)                
                self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                print self.ssh.accept_host
                if(self.ssh.accept_host.endswith(self.ssh.locate)):
                    for line in self.ssh.accept_host.splitlines():
                        msg= line
                    self.ssh.text.insert('end', msg)
                    self.ssh.text.tag_add("bold",'end-1line linestart','end-1line lineend')
                    break                
            except:
                pass
            finally:
                print 'finnallys'
        self.ssh.indexText = self.ssh.text.index('end-1c')
        self.ssh.text.yview('end')
        self.ssh.top_data = None
        self.ssh.dynamis_name = ''
        self.ssh.temp_store = []
        self.ssh.processing = False
        
        print 'adfadf'

class LS(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.rest=''
        self.flag_command = False
        
    def run(self):
        try:            
            finished= False
            time.sleep(0.1)
            #self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:
                    self.ssh.accept_host = self.ssh.channel.recv(1024)
                    if self.flag_command == True:                        
                        self.ssh.accept_host = self.rest + self.ssh.accept_host 
                        rs = re.sub(r'[^m]*m','',self.ssh.accept_host)
                        pos = rs.rfind('\n')
                        if pos>-1:
                            self.rest = rs[pos:]
                            rs = rs[:pos]                            
                        self.ssh.text.insert('end',rs)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        #end = ''
                        #for line in self.ssh.accept_host.split('\n'):
                        #   end = line
                                
                        if self.ssh.accept_host.strip().endswith(self.ssh.locate.strip())==True:
                            self.ssh.text.insert('end',self.rest)
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')    
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            finished= True     
                            break
                        

                    else:
                        pos = self.ssh.accept_host.find('\n')
                        self.ssh.accept_host = re.sub(r'[^m]*m','',self.ssh.accept_host)
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
            pass
        
        finally:
            print 'ls finnally'
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class LOGOUT_RUNNING(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        print '1'
        
    def run(self):
        try:
            finished= False
            #self.ssh.channel.send(self.command+"\n")
            #print self.ssh.channel.recv_ready()
            time.sleep(0.5)
            self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
            #print self.ssh.channel.recv_ready()
            #print self.ssh.indexText+'    ---------------'
            self.ssh.text.delete(self.ssh.indexText, 'end')
            
            while True:
                print self.ssh.accept_host+'   ...'
                if self.ssh.channel.recv_ready()==True:
                    print '1'
                    #print 'readddy'
                    self.ssh.text.insert('end',self.ssh.accept_host)
                    self.ssh.text.yview('end')
                    #time.sleep(0.2)
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    print '1.1'
                else:
                    print '2'
                    #print self.ssh.channel.in_buffer.read(1024, 1)
                    
                    #print self.ssh.channel.in_buffer.read(1024, 1)
                    #print len(self.ssh.channel.in_buffer._buffer)
                    self.ssh.text.insert('end',self.ssh.accept_host)
                    self.ssh.text.yview('end')
                    if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                        print '2.1'
                        self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                        finished= True
                        break
                    else:
                        try:
                            #print '2.2'                            
                            self.ssh.accept_host= self.ssh.channel.in_buffer.read(1024, 0.5)
                            #print self.ssh.accept_host
                            #print '2.3'
                        except:
                            print 'except'
                            break
                    
        except Exception as prt:
            self.ssh.top_data=None
            self.ssh.dynamis_name=''
            self.ssh.text.insert('end', '\n')
            self.ssh.text.insert('end', type(prt))
            self.ssh.text.insert('end', '\n'+self.ssh.locate)
            print self.ssh.locate
            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
            self.ssh.text.yview('end')            
            print 'errorwatting'
            print type(prt)
            print prt.args
            print 'a'
            #self.onBackForError()
        finally:
            print 'finnallys'
            self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')
                
class RUNNING_CAT(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        print '1'
        
    def run(self):
        try:
            finished= False
            #self.ssh.channel.send(self.command+"\n")
            #print self.ssh.channel.recv_ready()
            self.ssh.accept_host= self.ssh.channel.in_buffer.read(1024, 0.5)
            #print self.ssh.channel.recv_ready()
            #print self.ssh.indexText+'    ---------------'
            self.ssh.text.delete(self.ssh.indexText, 'end')
            print self.ssh.accept_host
            while self.ssh.accept_host:
                
                if self.ssh.channel.recv_ready()==True:
                    print '1'
                    #print 'readddy'
                    self.ssh.text.insert('end',self.ssh.accept_host)
                    self.ssh.text.yview('end')
                    #time.sleep(0.2)
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    print '1.1'
                else:
                    print '2'
                    #print self.ssh.channel.in_buffer.read(1024, 1)
                    
                    #print self.ssh.channel.in_buffer.read(1024, 1)
                    print len(self.ssh.channel.in_buffer._buffer)
                    self.ssh.text.insert('end',self.ssh.accept_host)
                    self.ssh.text.yview('end')
                    if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                        print '2.1'
                        self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                        finished= True
                        break
                    else:
                        try:
                            print '2.2'
                            self.ssh.accept_host= self.ssh.channel.in_buffer.read(1024, 0.5)
                            #print self.ssh.accept_host
                            #print '2.3'                        
                        except Exception :
                            print 'except '                            
                            break
             
        except Exception as prt:
            self.ssh.top_data=None
            self.ssh.dynamis_name=''
            self.ssh.text.insert('end', '\n')
            #self.ssh.text.insert('end', type(prt))
            self.ssh.text.insert('end', '\n'+self.ssh.locate)
            print self.ssh.locate
            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
            self.ssh.text.yview('end')            
            print 'errorwatting'
            print type(prt)
            print prt.args
            print 'a'
            #self.onBackForError()
        finally:
            print 'finnallys'
            self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')
                
class LOOP(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.count='0'
        self.previous=''
        
    def run(self):
        try:
            finished= False
            #self.ssh.channel.send(self.command+"\n")
            #print self.ssh.channel.recv_ready()
            self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
            #print self.ssh.channel.recv_ready()
            #print self.ssh.indexText+'    ---------------'
            self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:                
                if self.ssh.channel.recv_ready()==True:
                    print '1'
                    #print 'readddy'
                    self.ssh.text.insert('end',self.ssh.accept_host)
                    self.ssh.text.yview('end')
                    #time.sleep(0.2)
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    print '1.1'
                    self.count=0
                else:
                    print '2'
                    #print self.ssh.channel.in_buffer.read(1024, 1)
                    
                    #print self.ssh.channel.in_buffer.read(1024, 1)
                   
                    if self.previous != self.ssh.accept_host:
                        self.ssh.text.insert('end',self.ssh.accept_host)
                    self.previous = self.ssh.accept_host
                    self.ssh.text.yview('end')
                    if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                        print '2.1'
                        self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                        finished= True
                        break
                    else:
                        try:
                            print '2.2'
                            self.ssh.accept_host= self.ssh.channel.in_buffer.read(1024, 0.5)
                            print self.ssh.accept_host
                            print '2.3'
                        except:
                            pass
    
        except Exception as prt:
            self.ssh.top_data=None
            self.ssh.dynamis_name=''
            self.ssh.text.insert('end', '\n')
            self.ssh.text.insert('end', type(prt))
            self.ssh.text.insert('end', '\n'+self.ssh.locate)
            print self.ssh.locate
            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
            self.ssh.text.yview('end')            
            print 'errorwatting'
            print type(prt)
            print prt.args
            print 'a'
            #self.onBackForError()
        finally:
            print 'finnallys'
            self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')
                
class PASSWD(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.count='0'
        self.previous=''
        
    def run(self):
        try:
            finished= False
            #self.ssh.channel.send(self.command+"\n")
            #print self.ssh.channel.recv_ready()
            self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
            #print self.ssh.channel.recv_ready()
            #print self.ssh.indexText+'    ---------------'
            self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:                
                if self.ssh.channel.recv_ready()==True:
                    print 'recv_ready'
                    #print 'readddy'
                    self.ssh.text.insert('end',self.ssh.accept_host)
                    self.ssh.text.yview('end')
                    #time.sleep(0.2)
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    
                    self.count=0
                else:
                    print 'not recv_ready'
                    #print self.ssh.channel.in_buffer.read(1024, 1)
                    
                    #print self.ssh.channel.in_buffer.read(1024, 1)
                   
                    if self.previous != self.ssh.accept_host:
                        self.ssh.text.insert('end',self.ssh.accept_host)
                    self.previous = self.ssh.accept_host
                    self.ssh.text.yview('end')
                    if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                        print '2.1'
                        self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                        finished= True
                        break
                    else:
                        try:
                            print '2.2'
                            self.ssh.accept_host= self.ssh.channel.in_buffer.read(1024, 0.5)
                            print self.ssh.accept_host
                            print '2.3'
                        #except paramiko.buffered_pipe.PipeTimeout as e:                            
                            
                        #   print type(e)
                        except Exception as e:
                            self.count=0
                            print 'except '
                            print e
                            break
                
        except paramiko.buffered_pipe.PipeTimeout, e:
            print 'PipeTimeout'
            print type(e)      
        except Exception as prt:
            self.ssh.top_data=None
            self.ssh.dynamis_name=''
            self.ssh.text.insert('end', '\n')
            self.ssh.text.insert('end', type(prt))
            self.ssh.text.insert('end', '\n'+self.ssh.locate)
            print self.ssh.locate
            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
            self.ssh.text.yview('end')            
            print 'errorwatting'
            print type(prt)
            print prt.args
            print 'a'
            #self.onBackForError()
        finally:
            print 'finnallys'
            self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class PYTHON(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.flag_command = False
        
    def run(self):
        try:
            finished= False
            time.sleep(0.1)            
            while True:
                try:                    
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:
                        #print self.ssh.accept_host
                        self.ssh.text.insert('end',self.ssh.accept_host)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        #print self.ssh.indexText
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            #print self.ssh.channel.in_buffer.empty()
                            break
                        elif self.ssh.accept_host.find('>>>')>-1:
                            self.ssh.processing = False
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')                            
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                            elif self.ssh.accept_host.find('>>>')>-1:
                                self.ssh.processing = False
                        
                except:
                    print 'except'
                    pass
            
        except Exception as prt:
            print 'Exception'
            
        finally:
            print 'finnallys'
            self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_TREE(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.flag_command = False
        
    def run(self):
        try:            
            finished= False
            time.sleep(0.1)           
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:
                        self.ssh.text.insert('end',self.ssh.accept_host)
                        time.sleep(0.05)
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                                           
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            
                            break
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')                            
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break                            
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
          
        finally:
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_SORT(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.flag_command = False
        
    def run(self):
        try:
            finished= False
            time.sleep(0.1)
            #self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:                    
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:
                        self.ssh.text.insert('end',self.ssh.accept_host)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        self.ssh.processing = False
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            break
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            self.ssh.processing = False
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
      
        finally:
            self.ssh.processing = False
            if finished==True:
                print 'hoan thanh'
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')
                
class WAITING_HISTORY(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.flag_command = False
        
        
    def run(self):
        try:            
            finished= False
            time.sleep(0.1)           
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:                        
                        self.ssh.text.insert('end',self.ssh.accept_host)                       
                                               
                        if float(self.ssh.text.index('end'))>float(2000.0):
                            end = self.ssh.text.index('end linestart')
                            self.ssh.text.delete('1.0', float(end)-float(1000.0))
                        time.sleep(0.05)       
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')                        
                        end=''   
                        for line in self.ssh.accept_host.split("\n"):
                            end=line
                        if str(end) == str(self.ssh.locate):
                            print 'endrunning'
                            #print self.ssh.channel.eof_received
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            #self.ssh.channel.in_buffer.empty()'                            
                            break
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')                           
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                    
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
          
        finally:
            print 'finnallys'
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_RUNNING(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.flag_command = False
        
    def run(self):
        try:            
            finished= False
            time.sleep(0.1)
            #self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:
                        self.ssh.text.insert('end',self.ssh.accept_host)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        end = ''
                        for line in self.ssh.accept_host.split('\n'):
                            end = line 
                        if end.strip().endswith(self.ssh.locate.strip()):
                            print 'endrunning'
                            #print self.ssh.channel.eof_received
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            finished= True
                            #self.ssh.channel.in_buffer.empty()
                            break
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')                            
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception WAITING_RUNNING'
        
        finally:
            print 'finnallys'
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_LOGOUT(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.flag_command = False
        self.logoutMessage = ''
        
    def run(self):
        try:            
            finished= False
            time.sleep(1)
            #self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    self.ssh.accept_host = re.sub(r'\[H\[J','',self.ssh.accept_host)
                    print self.ssh.accept_host
                    print '...........'
                    if self.flag_command == True:
                        if self.ssh.accept_host.strip()=='':
                            self.ssh.processing = False
                            self.ssh.client.close();
                            self.ssh.toggle()
                            self.ssh.text.connected = False
                            msg = '\n'*50
                            self.ssh.text.insert('end', msg)
                            self.ssh.text.yview('end')
                            self.ssh.setttingForBeginning()
                            break
                        else:
                            self.ssh.text.insert('end',self.ssh.accept_host)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            end = ''
                            for line in self.ssh.accept_host.split('\n'):
                                end = line 
                            if end.strip().endswith(self.ssh.locate.strip()):
                                print 'endrunning'
                                #print self.ssh.channel.eof_received
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                finished= True
                                #self.ssh.channel.in_buffer.empty()
                                break
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')                            
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception WAITING_RUNNING'
        
        finally:
            print 'finnallys'
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_CD(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.flag_command = False
        
    def run(self):
        try:            
            finished= False
            time.sleep(0.1)           
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:                        
                        self.ssh.text.insert('end',self.ssh.accept_host)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        end = ''
                        for line in self.ssh.accept_host.split('\n'):
                            end = line                        
                        if end.find(self.ssh.accept_login)>-1:
                            print 'endrunning'
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= end
                            finished= True
                            #self.ssh.channel.in_buffer.empty()                            
                            break
                        
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')                            
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
      
        finally:
            print 'finnallys'
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_UNZIP(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.flag_command = False
        
    def run(self):
        try:
            
            finished= False
            time.sleep(0.1)            
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:                        
                        self.ssh.text.insert('end',self.ssh.accept_host)
                        time.sleep(0.05)
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                            #print 'endrunning'
                            #print self.ssh.channel.eof_received
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            #self.ssh.channel.in_buffer.empty()
                            break
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
            
        finally:
            print 'finnallys'
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_SU(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.flag_command = False
    def run(self):
        try:
            
            finished= False
            time.sleep(0.1)           
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:                        
                        if self.ssh.accept_host.strip().endswith(':'):
                            #print 'e'
                            #print list(self.ssh.accept_host.strip())==['\xbe', '\xcf', '\xc8', '\xa3', ':']
                            #if list(self.ssh.accept_host.strip())==['\xbe', '\xcf', '\xc8', '\xa3', ':']:
                            self.ssh.waitting = True
                        self.ssh.text.insert('end',self.ssh.accept_host)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1: 
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            #self.ssh.channel.in_buffer.empty()
                            break
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            if self.ssh.accept_host.strip().endswith(':'):                            
                                #if list(self.ssh.accept_host.strip())==['\xbe', '\xcf', '\xc8', '\xa3', ':']:
                                self.ssh.waitting = True
                                    
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
            
        finally:
            print 'finnallys'
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_LOGIN(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.flag_command = False
    def run(self):
        try:
            
            finished= False
            time.sleep(0.1)           
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:                      
                        self.ssh.text.insert('end',self.ssh.accept_host)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1: 
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            #self.ssh.channel.in_buffer.empty()
                            break
                        elif self.ssh.accept_host.strip().endswith(':'):
                            print list(self.ssh.accept_host.strip()) 
                            if self.ssh.accept_host.strip().endswith('login:') == False:
                                print 'waitingdsadlk'
                                self.ssh.waitting = True
                            self.ssh.processing = False
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                            elif self.ssh.accept_host.strip().endswith(':'):
                                if list(self.ssh.accept_host.strip())==['\xbe', '\xcf', '\xc8', '\xa3', ':']:
                                    self.ssh.waitting = True
                                self.ssh.processing = False
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
            
        finally:
            print 'finnallys'
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')


class WAITING_SH(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.flag_command = False
        
        
    def run(self):
        try:
            finished= False
            time.sleep(0.1)         
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:                    
                        self.ssh.text.insert('end',self.ssh.accept_host)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                            #print 'endrunning'
                            #print self.ssh.channel.eof_received
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            #self.ssh.channel.in_buffer.empty()
                            break
                        elif  self.ssh.accept_host.strip().endswith('$'):
                            self.ssh.processing = False
                            
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
            
        finally:
            print 'finnallys'
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class SLEEP(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.count='0'
        self.previous=''
        
    def run(self):
        try:
            finished= False
            time.sleep(0.3)
            self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                time.sleep(0.2)
                if self.ssh.channel.recv_ready() == True:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    self.ssh.text.insert('end',self.ssh.accept_host)
                    self.ssh.text.yview('end')
                    if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                        print '2.1'
                        self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                        finished= True
                        break
                      
             
        except Exception as prt:
            self.ssh.top_data=None
            self.ssh.dynamis_name=''
            self.ssh.text.insert('end', '\n')
            self.ssh.text.insert('end', type(prt))
            self.ssh.text.insert('end', '\n'+self.ssh.locate)
            print self.ssh.locate
            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
            self.ssh.text.yview('end')            
            print 'errorwatting'
            print type(prt)
            print prt.args
            print 'a'
            #self.onBackForError()
        finally:
            print 'finnallys'
            self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class TEST(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.count='0'
        self.previous=''
        
    def run(self):
        print self.ssh.text.index('insert')
        print '32334'
        print self.ssh.text.index('end')
        self.ssh.text.insert('24.34','adfadfa')  

class VI(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.count='0'
        self.previous=''
        
    def run(self):
        try:
            
            finished= False
            time.sleep(0.1)
            self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:
                    if self.ssh.channel.recv_ready()==True:
                        #print 'if'
                        #print self.ssh.channel.eof_received
                        self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                        self.ssh.text.insert('end',self.ssh.accept_host)                        
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        end = ''
                        for line in self.ssh.accept_host.split('\n'):
                            end = line 
                        if end.strip().endswith(self.ssh.locate.strip()):
                            print 'endrunning'
                            #print self.ssh.channel.eof_received
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            finished= True
                            #self.ssh.channel.in_buffer.empty()
                            
                            break
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
        
        finally:
            print 'finnallys'
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')
    
class VIS(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.firstLine = self.ssh.text.index('end')
        print 'firstLine'
        print self.firstLine
        print 'firstLine'
        self.clastLine = 1.0
        self.flag_command = False
        
    def convertStringToIndex(self, line):
        print line
        search = re.search(r'\[.*\H',line)
        print search
        if search:
            try:
                print 'convertStringToIndex'
                print search.group(0)
                search = re.sub(';','.',search.group(0))
                search = search[1:]
                search = search[:-1]
                print float(search)+float(self.firstLine)
                return float(search)
            except:
                return None
        else:
            return None
            
     
    def run(self):
        try:
            
            finished= False
            time.sleep(0.1)
            self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:
                    end = ''
                    if self.ssh.channel.recv_ready()==True:
                        if self.flag_command == True:
                            self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                            print self.ssh.accept_host
                            for line in self.ssh.accept_host.split('\x1b'):
                                if line.startswith('[') and line.strip().endswith('H~'):
                                    self.ssh.text.insert('end','\n~')  
                                elif len(line.strip())>0:
                                    print '1'
                                    index = self.convertStringToIndex(line)
                                    print '2'
                                    if index:
                                        self.ssh.text.insert(index, line)
                                    else:
                                        self.ssh.text.insert('end','\n'+line)
                            
                            self.ssh.text.yview('end')
                            
                            self.ssh.indexText = self.ssh.text.index('end-1c')                            
                            for line in self.ssh.accept_host.split('\n'):
                                end = line 
                            if end.strip().endswith(self.ssh.locate.strip()):                                
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                finished= True                                
                                break
                        else:
                            self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                            pos = self.ssh.accept_host.find('\n')
                            if pos > -1:
                                self.flag_command = True
                                firstContent = self.ssh.accept_host[:pos]
                                elseContent = self.ssh.accept_host[pos:]
                                self.ssh.text.insert('end',firstContent)
                                self.ssh.text.insert('end',elseContent)
                                self.ssh.text.yview('end')
                                for line in self.ssh.accept_host.split('\n'):
                                    end = line 
                                if end.strip().endswith(self.ssh.locate.strip()):                                
                                    self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                    finished= True                                
                                    break
                            else:
                                self.ssh.text.insert('end',self.ssh.accept_host)
                                self.ssh.text.yview('end')
                                for line in self.ssh.accept_host.split('\n'):
                                    end = line 
                                if end.strip().endswith(self.ssh.locate.strip()):                                
                                    self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                    finished= True                                
                                    break                                
                            
                        
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
        
        finally:
            print 'finnallys'
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')
                
class MYSQL(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.flag_command = False
        
    def run(self):
        try:
            finished= False
            self.ssh.waitting = False
            time.sleep(0.1)                  
            while True:
                try:                    
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:
                        self.ssh.text.insert('end',self.ssh.accept_host)
                        time.sleep(0.05)
                        self.ssh.text.yview('end')
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        #print self.ssh.indexText
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished = True
                            #print self.ssh.channel.in_buffer.empty()
                            break
                            
                        elif self.ssh.accept_host.find('mysql>')>-1:
                            print ' mysql>  mysql> '
                            self.ssh.processing = False                           
                                
                        elif self.ssh.accept_host.find('Enter password:')>-1:
                            self.ssh.processing = False
                            self.ssh.waitting = True
                            
                    else:
                        print '22222222222222'
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                            elif self.ssh.accept_host.find('mysql>')>-1:
                                print ' mysql>  mysql> '
                                self.ssh.processing = False                           
                                
                            elif self.ssh.accept_host.find('Enter password:')>-1:
                                self.ssh.processing = False
                                self.ssh.waitting = True
                        
                except:
                    print 'except'
                    pass
            
        except Exception as prt:
            print 'Exception'
            
        finally:
            print 'finnallys'
            self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')
    

class WAITING_MAN(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.end = False
        self.flag_command = False
        self.ssh.waitting = False
        self.index = 1.0
        self.manEnd = False
    def run(self):
        try: 
            finished= False
            time.sleep(0.1)
            #self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.manEnd == False:
                        if self.flag_command == True:
                            self.index = self.ssh.text.index('insert')
                            if self.ssh.text.get('insert-1c','insert')==':':
                                self.ssh.text.delete('insert-1c','insert')
                            if self.ssh.accept_host.strip().endswith('\n:[K') == True:
                                self.end = True
                            self.ssh.accept_host = re.sub(r'\[m|\[[1|0|4]m|\[K|\[\?1h\=|\[\?1l\>','',self.ssh.accept_host)
                            #self.ssh.accept_host = re.sub(r'\[K',' ',self.ssh.accept_host)
                            self.ssh.accept_host = re.sub(r'\n:','\n',self.ssh.accept_host)
                            end = re.search(r'\[7m\(END\)',self.ssh.accept_host)
                            if end != None:
                                self.ssh.waitting = True
                                self.ssh.accept_host = re.sub(r'\n.*$','\n(END)',self.ssh.accept_host)
                                self.manEnd = True
                            self.ssh.text.insert('end',self.ssh.accept_host)
                            time.sleep(0.05)
                            self.ssh.text.yview('end')                        
                            if self.end == True:
                                self.end = False 
                                self.ssh.text.insert('end',':')
                                self.ssh.processing = False
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:                            
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                self.ssh.processing = False
                                #self.ssh.channel.in_buffer.empty()
                                break
                        else:
                            pos = self.ssh.accept_host.find('\n')
                            if pos > -1:
                                self.flag_command = True
                                elseContent = self.ssh.accept_host[pos:]
                                self.ssh.text.insert('end',elseContent)                        
                                self.ssh.text.yview('end')
                                self.ssh.indexText = self.ssh.text.index('end-1c')
                                self.ssh.processing = False
                                if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                    self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                    self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                    finished= True
                                    break
                    else:
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                            self.ssh.text.insert('end','\n'+self.ssh.accept_host)
                            time.sleep(0.05)
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True
                            self.ssh.processing = False
                            #self.ssh.channel.in_buffer.empty()
                            break
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
           
        finally:
            print 'finnallys'
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_MORE(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.end = False
        self.endLine = None
        self.flag_command = False
        self.ssh.waitting = False
        self.index = 1.0
        self.present=''
    def run(self):
        try: 
            finished= False
            time.sleep(0.1)
            #self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    if self.flag_command == True:
                        self.index = self.ssh.text.index('insert')
                        self.present = self.ssh.text.get('insert linestart','insert').strip()
                        if re.search(r'--More--\([\d]{1,2}\%\)' , self.present) != None:
                            self.ssh.text.delete('insert linestart','insert')
                            
                        self.ssh.accept_host = re.sub(r'\[m|\[7m|\[K','',self.ssh.accept_host)
                        self.endLine = re.search(r'--More--\([\d]{1,2}\%\)$', self.ssh.accept_host.strip())
                       
                        #self.ssh.accept_host = re.sub(r'\[K',' ',self.ssh.accept_host)
                        print self.ssh.accept_host
                        self.ssh.accept_host = re.sub(r'--More--\([\d]{1,2}\%\)','',self.ssh.accept_host)
                        print self.ssh.accept_host
                        #end = re.search(r'\[7m\(END\)',self.ssh.accept_host)
                        #if end != None:
                        #   self.ssh.waitting = True
                        #  self.ssh.accept_host = re.sub(r'\[7m\(END\)','(END)',self.ssh.accept_host)                         
                        self.ssh.text.insert('end',self.ssh.accept_host)
                        time.sleep(0.05)
                        self.ssh.text.yview('end')                        
                        if self.endLine != None:                            
                            self.ssh.text.insert('end',self.endLine.group(0))
                            self.ssh.processing = False
                        self.ssh.indexText = self.ssh.text.index('end-1c')
                        if self.ssh.accept_host.find(self.ssh.accept_login)>-1:                            
                            self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                            finished= True                            
                            #self.ssh.channel.in_buffer.empty()
                            break
                    else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            elseContent = self.ssh.accept_host[pos:]
                            self.ssh.text.insert('end',elseContent)                        
                            self.ssh.text.yview('end')
                            self.ssh.indexText = self.ssh.text.index('end-1c')
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
           
        finally:
            print 'finnallys'
            self.ssh.processing = False
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')
                self.ssh.processing = False

class WAITING_DD(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.count='0'
        self.previous=''
        
    def run(self):
        try: 
            finished= False
            time.sleep(0.1)
            self.ssh.text.delete(self.ssh.indexText, 'end')            
            while True:
                try:
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
                    self.ssh.text.insert('end',self.ssh.accept_host)
                    self.ssh.text.yview('end')
                    self.ssh.processing = False
                    self.ssh.indexText = self.ssh.text.index('end-1c')
                    if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                        #print 'endrunning'
                        #print self.ssh.channel.eof_received
                        self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                        finished= True
                        #self.ssh.channel.in_buffer.empty()
                        break
                except:
                    pass
            
        except Exception as prt:
            print 'Exception'
            
        finally:
            print 'finnallys'
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            self.ssh.processing = False
            #print str(finished)+'finisheds'
            #print '-----------:'+self.ssh.indexText
            if finished==True:
                self.ssh.top_data=None
                self.ssh.dynamis_name=''
                self.ssh.text.yview('end')

class WAITING_TOPs(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.topIndex = float(self.ssh.text.index('end'))-1
        self.index = float(self.topIndex)
        print 'begin'
        print self.index
        self.maxIndex = self.index+50
        print self.maxIndex
        print 'end'
        self.saveATime = ''
        self.content =''
        self.content_Len = 0
        self.temp = ''
        self.temp_Len = 0
        self.flag_command=False
        
    def run(self):
        try:         
            time.sleep(0.1)
            #self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
            #print self.ssh.indexText+'    ---------------'
            #self.ssh.text.delete(self.ssh.indexText,'end')
            count=0;
            lineStop = ''
            while True:
                #self.index = float(self.topIndex)
                self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)               
                if self.flag_command == True:
                    self.ssh.accept_host = self.saveATime + self.ssh.accept_host
                    self.ssh.accept_host = re.sub(r'\[m|\[K|\[m|\[7m|\[H|\[J','',self.ssh.accept_host)
                    pos = self.ssh.accept_host.rfind('\n')                  
                    self.saveATime = ''
                    if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                        if lineStop.find('Stopped')>-1:
                            self.ssh.text.insert(Tkinter.END,'\n'+lineStop+'\n')
                            lineStop=''
                        self.ssh.text.insert(Tkinter.END,self.ssh.accept_host)
                        self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.ssh.text.yview('end')
                        self.ssh.accept_host = ''
                        self.ssh.top_data = None
                        self.ssh.dynamis_name=''
                        self.ssh.indexText = self.ssh.text.index('end-1c')                   
                        break
                    
                    else:           
                        self.content = self.ssh.text.get(self.topIndex,'end')
                        self.content_Len = self.content.splitlines()
                        
                        #lineStop=self.temp.strip().rsplit('\n')[0]
                        
                        if(self.ssh.accept_host.find('top -')>-1):
                            print 'top'
                            self.index = float(self.topIndex)
                            self.ssh.accept_host = re.sub(r'\[6\;1H',' ',self.ssh.accept_host)
                            print self.ssh.accept_host
                            print len(self.ssh.accept_host.splitlines())
                            print '.......................'
                            self.temp = self.ssh.accept_host.strip()
                            self.temp_Len = self.temp.splitlines()
                            
                            if len(self.content_Len)>= len(self.temp_Len):
                                print 'content >='
                                for i,line in enumerate(self.content_Len):
                                    self.index += 1
                                    print self.index
                                    if i<=50:
                                        print '<=50'
                                        if i<len(self.temp_Len):                                            
                                            print 'temp'
                                            print self.temp_Len[i]
                                            self.ssh.text.delete(self.index, self.index+1)
                                            self.ssh.text.insert(self.index, '\n'+self.temp_Len[i])
                                        else:
                                            print 'content'
                                            print line
                                            
                                            print self.ssh.text.index('end')
                                            self.ssh.text.delete(self.index,self.index+1)                                            
                                            self.ssh.text.insert(self.index, '\n'+line)
                                    else:
                                        print '>50'
                                        #self.ssh.text.delete(self.index,'end')
                                        #break
                                    
                            else:
                                print 'temp >'
                                for i,line in enumerate(self.temp_Len):
                                    self.index += 1
                                    print self.index
                                    print line
                                    #self.ssh.text.mark_set('insert',self.index)
                                    print self.ssh.text.index('end')
                                    #self.ssh.text.focus_set()
                                    #self.ssh.text.delete('insert linestart','insert lineend')
                                    self.ssh.text.insert(self.index, '\n'+line)
                                
                        else:
                            print 'not top'
                            self.ssh.accept_host = re.sub(r'\[6\;1H',' ',self.ssh.accept_host)
                            print self.ssh.accept_host
                            print len(self.ssh.accept_host.splitlines())
                            print '.......................'
                            self.temp = self.ssh.accept_host.strip()
                            self.temp_Len = self.temp.splitlines()
                            self.temp = re.sub(r'\[6\;1H','\n',self.temp)
                            if len(self.temp.strip())>0:
                                print 'data'
                                if self.index>=self.maxIndex:
                                    print '>=50'
                                    #self.ssh.text.delete(self.index,'end')
                                    #break
   
                                else:
                                    print '<50'
                                    self.ssh.text.delete('end-1c','end')
                                    for i,line in enumerate(self.temp_Len):
                                        self.index += 1
                                        print self.index
                                        print line
                                        self.ssh.text.delete(self.index,self.index+1)
                                        self.ssh.text.insert(self.index, line+'\n')
                                         
                            else:
                                print 'null'
                                #break
                                
                            
                        self.ssh.text.yview(self.ssh.indexText)                    
                        
                else:
                        pos = self.ssh.accept_host.find('\n')
                        if pos > -1:
                            self.flag_command = True
                            self.saveATime = self.ssh.accept_host[pos:]                           
                            self.ssh.processing = False
                            if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                                self.ssh.text.insert('end',self.saveATime)                        
                                self.ssh.text.yview('end')
                                self.ssh.indexText = self.ssh.text.index('end-1c')
                                self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.ssh.locate= self.ssh.text.get('end-1line linestart','end-1line lineend')
                                finished= True
                                break
            
        except Exception as prt:
            print 'errorwatting'
            print 'error else '+str(prt)
            #self.onBackForError()
        finally:
            print 'finnallys'
            self.ssh.top_data=None
            self.ssh.dynamis_name=''
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            print '-----------:'+self.ssh.indexText

class WAITING_TOP(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.topIndex = float(self.ssh.text.index('end'))
        self.flag_command = False
        self.flag_rest = ''
        self.flag_top = True
        self.count = 0
        self.flag_newLine = False

        self.secondLine = ''
        self.temp = ''
        self.tempIndex = self.topIndex-1

        self.previousTop = True

        self.stopLine = None
        
    def run(self):
        try:           
            time.sleep(0.1)
            while True:                
                self.ssh.accept_host = self.flag_rest + self.ssh.channel.recv(1024).decode(self.ssh.charset)
                #print self.ssh.accept_host
                #print '................'
                #print list(self.ssh.accept_host)
                #print re.search(r'^(\[m)',self.ssh.accept_host.lstrip())
                self.ssh.accept_host = re.sub(r'\[m|\[K|\[m|\[7m|\[H|\[J','',self.ssh.accept_host)
                self.ssh.accept_host = re.sub(r'\[6\;1H|\[51\;1H',' ',self.ssh.accept_host)
                #print self.ssh.accept_host
                #print '................'
                #print list(self.ssh.accept_host)
                if len(self.ssh.accept_host.splitlines())>=2:
                    self.secondLine = self.ssh.accept_host.split('\n')[1]
                    if len(self.secondLine.strip())==0:
                        self.flag_newLine = True
                    else:
                        self.flag_newLine = False
                
                if self.count < 2:
                    if self.ssh.accept_host.find('top-') > -1 or self.ssh.accept_host.find('Cpu(s):') > -1:
                        self.flag_top = True
                        self.previousTop = True
                    else:
                        self.flag_top = False
                        
                if self.flag_command == True:
                    if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                        #print list(self.stopLine)
                        if self.stopLine != None:
                            temp = re.search(r'\[$', self.stopLine)
                            if temp!=None:
                                self.ssh.text.insert('end','\n'+temp.group(0)+'\n')
                            else:
                                self.ssh.text.insert('end','\n'+self.stopLine+'\n')
                             
                        print self.ssh.text.index('end')
                        #self.ssh.accept_host = re.sub(r'^.*\n','\n',self.ssh.accept_host)
                        self.ssh.text.insert(Tkinter.END,self.ssh.accept_host)
                        self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.ssh.text.yview('end')
                        self.ssh.accept_host = ''
                        self.ssh.top_data = None
                        self.ssh.dynamis_name=''
                        self.ssh.indexText = self.ssh.text.index('end-1c')                   
                        break
                
                    if self.flag_top == True:                        
                        self.temp = self.ssh.accept_host.lstrip()
                        if self.topIndex == float(self.ssh.text.index('end')):
                            self.ssh.text.delete(self.topIndex,'end')
                            time.sleep(0.05)
                            self.ssh.text.insert('end','\n'+self.temp)
                            self.tempIndex = self.ssh.text.index('end')                            
                        else:
                            #self.temp = re.sub(r'(\n.*)$','',self.temp)
                            self.tempIndex = self.topIndex-1
                            lenght = len(self.temp.strip().splitlines())-1
                            self.tempIndex = float(self.tempIndex)
                            for i,line in enumerate(self.temp.splitlines()):
                                self.tempIndex +=1
                                if line.find('Stopped')>-1:
                                    self.stopLine = line
                                    break
                                if i<lenght:                                                                                              
                                    #print 'tempIndex'
                                    #print self.tempIndex
                                    #print self.tempIndex+1
                                    #print line
                                    self.ssh.text.delete(self.tempIndex,self.tempIndex+1)
                                    time.sleep(0.05)
                                    self.ssh.text.insert(self.tempIndex,line+'\n')
                                else:
                                    self.ssh.text.delete(self.tempIndex,self.tempIndex+1)
                                    time.sleep(0.05)
                                    self.ssh.text.insert(self.tempIndex,line+'\n')                                    
                                    break
                                #break
                            #break
                            #
                            #self.tempIndex = self.tempIndex+1
                            #print self.tempIndex
                            #print float(self.ssh.text.index('end'))
                            #break
                    else:
                        #print self.tempIndex
                        #print float(self.ssh.text.index('end'))
                        if len(self.ssh.accept_host.strip())>0:
                            #print 'a'
                            if float(self.tempIndex) == float(self.ssh.text.index('end')):
                                #print 'b'
                                if self.previousTop == True:
                                    self.ssh.text.delete(self.tempIndex,'end')
                                    self.previousTop = False
                                    
                                if self.flag_newLine == True:
                                    self.ssh.accept_host = re.sub(r'^(.*\n)','',self.ssh.accept_host)
                                    self.ssh.text.insert('end',self.ssh.accept_host)
                                                                    
                                else:                            
                                    self.ssh.accept_host = re.sub(r'^(.*\n)','',self.ssh.accept_host)
                                    self.ssh.text.insert('end',self.ssh.accept_host)
                                self.tempIndex = float(self.ssh.text.index('end'))
                            else:
                                #print '1'
                                self.temp = re.sub(r'^(.*\n)','',self.ssh.accept_host)                                
                                #print '..'+self.temp.split('\n')[0]+'..'
                                #print '2'
                                endLine = self.ssh.text.get(self.tempIndex,self.tempIndex+1)
                                endLine = re.sub(r'(\n.*)$','',endLine)
                                #print '..'+endLine+'..'
                                self.temp = endLine + self.temp
                                lenght = len(self.temp.splitlines())-1
                                self.tempIndex = float(self.tempIndex)-1
                                for i,line in enumerate(self.temp.splitlines()):
                                    self.tempIndex += 1
                                    if line.find('Stopped')>-1:
                                        self.stopLine = line
                                        break
                                    if i<lenght:                                                                                                                          
                                        #print '3'
                                        #print line
                                        self.ssh.text.delete(self.tempIndex,float(self.tempIndex)+1)
                                        time.sleep(0.05)
                                        self.ssh.text.insert(self.tempIndex,line+'\n')
                                    else:
                                        #print '4'
                                        self.ssh.text.delete(self.tempIndex,self.tempIndex+1)
                                        time.sleep(0.05)
                                        self.ssh.text.insert(self.tempIndex,line+'\n')
                                #break 
                                                                
                else:
                    pos = self.ssh.accept_host.find('\n')
                    if pos > -1:
                        self.flag_command = True
                        self.flag_rest = self.ssh.accept_host[pos:]
                        
                self.ssh.text.yview(self.topIndex)

            
        except Exception as prt:
            print 'errorwatting'
            print 'error else '+str(prt)
            #self.onBackForError()
        finally:
            print 'finnallys'
            self.ssh.top_data=None
            self.ssh.dynamis_name=''
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            print '-----------:'+self.ssh.indexText

class WAITING_DATA(threading.Thread):
    def __init__(self,ssh, command, mode = None):
        threading.Thread.__init__(self) 
        self.ssh=ssh
        self.command= command
        self.content =''
        self.content_Len = 0
        self.temp = ''
        self.temp_Len = 0
        
    def run(self):
        try:
            self.ssh.channel.send(self.command+"\n")            
            time.sleep(0.5)
            self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
            print self.ssh.indexText+'    ---------------'
            #self.ssh.text.delete(self.ssh.indexText,'end')
            count=0;
            lineStop = ''
            while self.ssh.accept_host != '':
                
                if self.ssh.accept_host.find(self.ssh.accept_login)>-1:
                    if lineStop.find('Stopped')>-1:
                        self.ssh.text.insert(Tkinter.END,'\n'+lineStop+'\n')
                        lineStop=''
                    self.ssh.text.insert(Tkinter.END,self.ssh.accept_host)
                    self.ssh.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                    self.ssh.text.yview('end')
                    self.ssh.accept_host = ''
                    self.ssh.top_data = None
                    self.ssh.dynamis_name=''
                    self.ssh.indexText = self.ssh.text.index('end-1c')                   
                    break
                else:
                   
                    if self.ssh.accept_host.split('\n')[0].strip()=='top':                        
                        self.ssh.accept_host = self.ssh.accept_host[self.ssh.accept_host.find('\n'):]
                    self.content = self.ssh.text.get(self.ssh.indexText,'end')
                    self.content_Len = self.content.splitlines()
                    self.temp = self.ssh.accept_host
                    self.temp_Len = self.temp.splitlines()
                    lineStop=self.temp.strip().rsplit('\n')[0]
                    
                    if(self.ssh.accept_host.find('top -')>-1):
                        
                        self.ssh.text.delete(self.ssh.indexText,'end')
                       
                        if len(self.content_Len)>=len(self.temp_Len):
                            if len(self.temp_Len)<49:
                                print '1'
                                for i,line in enumerate(self.content_Len):
                                    if i<len(self.temp_Len):
                                        if len(self.temp_Len[i])==0:
                                            #print '2'+line
                                            self.ssh.text.insert('end', '\n'+line)
                                        else:
                                            #print '3'+self.temp_Len[i]
                                            self.ssh.text.insert('end', '\n'+self.temp_Len[i])
                                    else:
                                        break
                            else:
                                print '2'
                                for i,line in enumerate(self.content_Len):
                                    
                                    if i<len(self.temp_Len):
                                        if len(self.temp_Len[i])==0:
                                            #print '2'+line
                                            self.ssh.text.insert('end', '\n'+line)
                                        else:
                                            #print '3'+self.temp_Len[i]
                                            self.ssh.text.insert('end', '\n'+self.temp_Len[i])
                                    else:
                                        #print '4'+line
                                        self.ssh.text.insert('end', '\n'+line)
                        else:
                            self.ssh.text.insert('end', '\n'+self.temp)
                            '''for i,line in enumerate(self.temp_Len):                                
                                if i<len(self.content_Len):
                                    if len(line)==0:
                                        #print '5'
                                        self.ssh.text.insert('end', '\n'+self.content_Len[i])
                                    else:
                                        #print '6'
                                        self.ssh.text.insert('end', '\n'+line)
                                else:
                                    #print '7'
                                    self.ssh.text.insert('end', '\n'+line)'''
                    else:
                        print '3'
                        if len(self.content_Len)<50:                            
                            self.ssh.text.delete('end-1c','end')
                            else_Len = 50 - len(self.content_Len)
                            for i,line in enumerate(self.temp_Len):
                                if i <= else_Len:
                                    self.ssh.text.insert('end',line+'\n')
                                else:
                                    break
                        
                        
                    self.ssh.text.yview(self.ssh.indexText)                    
                    self.ssh.accept_host= self.ssh.channel.recv(1024).decode(self.ssh.charset)
            
        except Exception as prt:
            print 'errorwatting'
            print 'error else '+str(prt)
            #self.onBackForError()
        finally:
            print 'finnallys'
            self.ssh.top_data=None
            self.ssh.dynamis_name=''
            #self.ssh.indexText = self.ssh.text.index('end-1c')
            print '-----------:'+self.ssh.indexText
            
            
class DYNAMIC_DATA(threading.Thread):
    def __init__(self, data, stderr, ssh, mode = None):
        threading.Thread.__init__(self)
        self.d_data = data
        self.d_err = stderr
        self.mode = mode
        self.data = ""
        self.data_store = ""
        self.data_top = ""
        self.count = 0
        self.ssh = ssh
        self.stop = False       

    def run(self):
        while True:
            if self.ssh.dynamis_name == None:
                break
            data = str(self.d_data.readline())
            if len(data) != 0:
                self.count += 1
                if self.mode == None:
                    print 'None'
                    self.ssh.text.insert(Tkinter.END, data)
                else:
                    if self.data == "":
                        self.data = self.ssh.text.get(1.0, Tkinter.END)                        
                        self.ssh.text.delete('end-1c','end')
                        self.ssh.topIndex = self.ssh.text.index(Tkinter.END)                        
                    if data.find("top -") != 0:
                        self.data_store += data
                    else:
                        data = data + self.data_store
                        print data
                        print '...'
                        self.stop = True 
                        self.ssh.text.delete(self.ssh.topIndex, Tkinter.END)
                        for i,line in enumerate(data.splitlines()):
                            if i>50:
                                break
                            self.ssh.text.insert('end', "\n"+ line)
                        self.ssh.text.yview(self.ssh.topIndex)
                        self.data_store = ""
            else:
                print self.d_err.read()
                self.ssh.text.delete('end-1c','end')
                self.ssh.topIndex = self.ssh.text.index(Tkinter.END) 
                self.stop = True                   
                self.ssh.text.delete(self.ssh.topIndex, Tkinter.END)                       
                self.ssh.text.insert(self.ssh.topIndex, "\n"+ self.d_err.read())                
                self.data_store = ""
                self.ssh.dynamis_name = None
                self.ssh.top_data = None
                self.ssh.text.config(state=NORMAL) 
                self.ssh.onQuitTheading()
                self.ssh.comments_temp = ""
                break
            
         
class SSH(threading.Thread, Tkinter.Frame):
    def toggle(self, event=None):
        if self.filemenu.entrycget(1,"state")=="normal":
            self.filemenu.entryconfig(2,state=NORMAL)
            self.filemenu.entryconfig(1,state=DISABLED)
        else:
            self.filemenu.entryconfig(1,state=NORMAL)
            self.filemenu.entryconfig(2,state=DISABLED)
            
    def __init__(self, master):
        Tkinter.Frame.__init__(self, master)
        threading.Thread.__init__(self)
        self.master = master
    
        # Set Title window and Create the menu
        self.master.title("Elisoft CRT")
        self.menu = Tkinter.Menu(self)
        
        self.master.config(menu=self.menu)
        self.menubar = Tkinter.Menu(self.menu)
        
        # Create Menu File
        self.filemenu = Tkinter.Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="New", command=self.OnConnect)
        self.filemenu.add_command(label="Connect", command=self.OnOpenConnect)
        self.filemenu.add_command(label="Disconnect",command=self.OnCloseConnect,state=DISABLED)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self.OnExit)
        self.menu.add_cascade(label="File", menu=self.filemenu)

        # Create Menu Process
        self.processmenu = Tkinter.Menu(self.menubar, tearoff=0)
        self.processmenu.add_command(label="Send File", command=self.OnSendFile)
        self.menu.add_cascade(label="Process", menu=self.processmenu)

        # Create Menu update
        self.updateMenu = Tkinter.Menu(self.menubar, tearoff=0)
        self.updateMenu.add_command(label="Update", command=self.updateApp)
        self.menu.add_cascade(label="Update", menu=self.updateMenu)

        # Create Scroll Bar
        self.scrollbar = Tkinter.Scrollbar(self.master)
        self.scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)

        # Create Text Field
        self.text = Tkinter.Text(self.master, height=50, width=100, yscrollcommand=self.scrollbar.set)
        self.text.grid(row=0, column=0)


        #self.text.bind('<KeyRelease>', self.SEND_DIRECT)
        self.text.bind('<Button-1>', self.OnClick)
        #self.text.bind('<Return>', self.OnSendMessage)
        self.text.bind('<BackSpace>', self.OnDisBksp)
        self.text.bind('<Delete>', self.OnDisDelete)
        self.text.bind('<Up>', self.OnDisUp)
        self.text.bind('<Down>', self.OnDisDown)
        self.text.bind('<Left>', self.OnDisLeft)
        self.text.bind('<Right>', self.OnDisRight)
        self.text.bind('<ButtonRelease-1>', self.release1 )
        #self.text.bind('<B1-Motion>', self.motion )
        #self.text.bind('<Motion>', self.motion )
        #self.text.bind('<Double-Button-1>',lambda e: 'break' )
        self.text.bind('<Key>', self.key)
        self.text.pack()
        
        #save the index last for the text
        self.indexText = self.text.index(Tkinter.INSERT)
        self.scrollbar.config(command=self.text.yview)

        bold_font = tkFont.Font(self.text, self.text.cget("font"))
        bold_font.configure(weight="bold", size=12)
        self.text.tag_configure("bold", font=bold_font)
        self.text.connected = False
        self.charset = 'euc-kr'
        self.setttingForBeginning()
               
        
    def setttingForBeginning(self):
        # Param of SSH
        self.command = "ssh> "
        self.len_command = 0
        self.length_char = 0
        self.processing = False
        self.disable_text = ""
        self.char_last_text = ""
        self.msg_edit = ""
        self.msg = ""
        self.cmd = ""
        self.contents = ""
        self.contents2 = ""
        self.comments = ""
        self.comments_temp = ""
        self.previous_command = ""
        self.top_data = None
        self.ipaddress = self.getPublicIp()
        self.current_folder = "."
        self.connect_folder = ""
        self.accept_login=''
        self.locate='ssh> '

        #Param of dynamis
        self.channel=None
        self.dynamis_name = None
        self.topIndex = 1.0
        self.endIndex = 1.0
        self.filename = ""
        self.waitting = False
        self.temp_store = []
        self.temp_lenght = -1
        self.tempArray = []
        self.vi_default =['exit','qcr','q','Q','!q','wq','x']
        self.lenght= 1
        self.press_key = False

        #Param of SFTP
        self.sftp_host = ''
        self.sftp_port = 22
        self.sftp_username = ''
        self.sftp_password = ''
        self.sftp_msg = ''
        self.sftp_process = False
        self.sftp_check_password = False
        self.sftp_check_login = False
        self.sftp_maintain = False
        self.stdin=None
        self.stdout=None
        self.sftp=None

        # Variable Configure
        self.text.config(state=Tkinter.DISABLED)
        self.fileopen = self.getPathDocument() + r"\py_ssh.data"
        
        #self.current_work = ""
        self.numkeywait = 0
        self.editmode = False
        self.listBold = []
        self.command_store = []
        self.command_key = -1
        self.input_command_len = 0
        self.disleft = False
        self.text.config(state=DISABLED)
        print 'setttingForBeginning'

    def key3(self, event):
        print repr(event)
        print event.keycode
        print '   code'
        print event.char
        print '   char'
        print event.keysym
        print '   keysym'
        print '--'
        pass

    def key2(self, event):        
        msg=''
        if len(event.keysym)>len(event.char):
            msg= event.char
        else:
            msg= event.keysym
        self.channel.send(msg)
        while True:
            if self.channel.recv_ready()==True:
                msg= self.channel.recv(1024)
            else:
                try:
                    msg= self.channel.in_buffer.read(1024, 0.5)
                except:
                    break
            break
        if event.keysym=='Return':
            print msg

    def SEND_DIRECT(self,event):
        if self.top_data != None:
            if self.dynamis_name=='CAT':                
                msg= self.text.get('end-2c','end')
                print msg+'msg'
                self.channel.sendall(msg)
            
    def key(self, event):        
        try:
            #print repr(event)
            #print event.keycode
            #print event.char
            #print event.keysym
            #print '--'
            if self.text.connected == False:
                return 'break'
            if self.top_data == None:
               
                if(self.processing == True):
                    #self.text.delete('insert-1c','insert')
                    #self.text.mark_set('insert','end')
                    print 'processing'
                    return 'break'               
                
                            
                elif event.keysym=='Return':
                    #print self.indexText
                    #print self.text.index('insert lineend')                    
                    self.comments = self.text.get(self.indexText, 'insert lineend')
                    #print '1'
                    #print self.comments
                    #print '2'
                    #self.comments = 'top'
                    self.processing = True
                    self.text.mark_set('insert','end')
                    self.OnSendMessage()                
                    self.comments=""                                      
                    #self.processing = False
                    self.comments_temp = ""
                    return 'break'
                                      
                    
                elif event.char == event.keysym or event.char == '!' or event.char == '@' or event.char == '#' or event.char == '$' or event.char == '%' or event.char == '^' or event.char == '&' or event.char == '*' or event.char == '(' or event.char == ')' or event.char == '_' or event.char == '+' or event.char == '|' or event.char == '"' or event.char == '}' or event.char == '{' or event.char == ':' or event.char == '<' or event.char == '>' or event.char == '?' or event.char == '~':
                    self.comments_temp += event.char
                    print 'indextext: '+self.indexText+'='+self.text.index(Tkinter.END)+'='+self.comments

                elif event.keysym == 'minus' or event.keysym == 'quoteright' or event.keysym == 'period' or event.keysym == 'slash' or event.keysym == 'semicolon' or event.keysym == 'underscore' or event.keysym == 'space' or event.keysym == 'equal':
                    self.comments_temp += event.char
                    print 'indextext: '+self.indexText+'='+self.text.index(Tkinter.END)+'='+self.comments
                  
                elif event.keysym == 'BackSpace':
                    self.comments = self.text.get(self.indexText, Tkinter.END)
                    print "back: "+self.comments
                    
                elif event.keysym == 'Delete':
                    self.comments = self.text.get(self.indexText, Tkinter.END)
                    print "delete: "+self.comments
                
                else:
                    print event.char
                    print 'Special Key %r' % event.keysym
                    return 'break'
            else:
                if self.dynamis_name == None:
                    print 'self.dynamis_name'
                    return 'break'                                                         
                
                elif self.dynamis_name=='WAITTING':
                    if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                        self.top_data=None
                        self.dynamis_name=""
                    elif event.keysym == 'Return':
                        msg = self.text.get(self.indexText,'end')                       
                        self.channel.send( msg.strip()+"\n")
                        time.sleep(0.5)
                        self.accept_host = self.channel.recv(1024)
                        finished= False
                        self.text.delete(self.indexText,'endef keyd')
                        while self.accept_host:
                            print self.channel.recv_ready()
                            print '..'
                            if self.channel.recv_ready()==True:
                                self.text.insert(Tkinter.END,self.accept_host)
                                self.text.yview('end')
                                time.sleep(0.2)
                                self.accept_host= self.channel.recv(1024)
                            else:
                                self.text.insert(Tkinter.END,self.accept_host)
                                if self.accept_host.find(self.accept_login)>-1:                       
                                    self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')                        
                                    finished= True
                                self.text.yview('end')
                                
                                break
                        if finished== True:
                            print 'finished'
                            self.top_data=None
                            self.dynamis_name=""                   
                        self.indexText= self.text.index('end-1c')
                        print self.indexText
                        return 'break'
                    
                elif self.dynamis_name=='DD':
                    #print event.char
                    if self.processing == True:
                        return 'break'
                    if self.comments_temp == 'Control_L' and (event.keysym == 'z' or event.keysym=='d'):
                        self.channel.send(event.char)
                                                
                    elif event.keysym=='Return':                        
                        if self.waitting == False:
                            self.processing = True                        
                            self.channel.send('\n')
                            #self.text.delete('insert-1c','insert')
                            return 'break'
                        else:
                            return 'break'
                    self.comments_temp = event.keysym
                        
                elif self.dynamis_name=='MAN':
                    #print event.char
                    #if self.processing == True:
                    #   return 'break'
                    if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                        self.channel.send(event.char)                        
                                                
                    elif event.keysym=='Return':                        
                        if self.waitting == False:
                            self.processing = True                            
                            self.channel.send('\n')
                            #time.sleep(0.1)
                            #self.channel.send('\n')
                            #self.text.delete('insert-1c','insert')
                            return 'break'
                        else:
                            return 'break'
    
                    self.comments_temp = event.keysym
                   
                    return 'break'
                    
                elif self.dynamis_name=='MORE':                    
                    #print event.char
                    if self.processing == True:
                        return 'break'
                    if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                        self.channel.send(event.char)                        
                                                
                    elif event.keysym=='Return':                        
                        if self.waitting == False:
                            self.processing = True                            
                            self.channel.send('\n\n')
                            #time.sleep(0.1)
                            #self.channel.send('\n')
                            #self.text.delete('insert-1c','insert')
                            return 'break'
                        else:
                            return 'break'
    
                    self.comments_temp = event.keysym
                   
                    return 'break'
                

                elif self.dynamis_name=='PASSWD':                    
                    if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                        self.top_data = None
                        self.dynamis_name = ""
                        self.processing = False
                        self.temp_store = []
                    elif event.keysym == 'Return':
                        print self.processing
                        if self.processing==True:
                            print 'processsing'
                            return 'break'
                        self.processing=True
                    
                        try:
                            msg = ''
                            for line in self.temp_store:
                                msg+=line
                            self.temp_store=[]
                            self.channel.send( msg+"\n")
                            print msg+'  msg'
                            time.sleep(0.5)
                            self.accept_host = self.channel.recv(1024)
                            print self.accept_host
                            finished= False                            
                            while True:
                                if self.channel.recv_ready()==True:
                                    self.text.insert(Tkinter.END,self.accept_host)
                                    self.text.yview('end')
                                    time.sleep(0.2)
                                    self.accept_host= self.channel.recv(1024)
                                else:
                                    self.text.insert(Tkinter.END,self.accept_host)
                                    if self.accept_host.find(self.accept_login)>-1:                       
                                        self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')                        
                                        finished= True
                                    elif self.accept_host.find('password:')==-1:
                                        print 'go_on'
                                        GO_ON(self).start()                                        
                                    else:
                                        self.processing = False
                                    break
                                                        
                        except Exception,e:
                            print e
                            pass
                        finally:
                            if finished== True:
                                print 'finished'
                                self.top_data = None
                                self.dynamis_name = ""                                
                                self.processing = False
                            self.text.yview('end')
                            self.indexText= self.text.index('end-1c')
                    self.temp_store.append(event.char)
                    return 'break'
                elif self.dynamis_name=='CAT':
                    if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                        msg = self.text.get('insert linestart','insert lineend')+"\n"                        
                        self.channel.send(msg)
                        self.channel.send(event.char)
                        time.sleep(0.5)
                        while True:
                            if self.channel.recv_ready()==True:
                                self.accept_host = self.channel.recv(1024)
                                last = ''
                                beforeLast = ''
                                for line in self.accept_host.splitlines():
                                    beforeLast = last
                                    last = line                                    
        
                                if last.find(self.accept_login)>-1:
                                    self.text.insert(Tkinter.END, "\n"+beforeLast)
                                    self.text.insert(Tkinter.END, "\n"+last)
                                    self.text.tag_add("bold", 'end-1line linestart','end-1line lineend') 
                            else:
                                try:
                                    self.accept_host = self.channel.in_buffer.read(1024, 0.5)
                                    for line in self.accept_host.splitlines():
                                        beforeLast = last
                                        last = line                                    
        
                                    if last.find(self.accept_login)>-1:
                                        self.text.insert(Tkinter.END, "\n"+beforeLast)
                                        self.text.insert(Tkinter.END, "\n"+last)
                                        self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                except:
                                    break
                                break
                        self.top_data = None
                        self.dynamis_name = ""
                        self.indexText = self.text.index('end-1c')
                        self.text.yview('end')
                    elif event.keysym == 'Return':
                        msg = self.text.get('insert linestart','insert lineend')
                        self.text.delete(self.indexText,'end')
                        print msg
                        self.channel.send(msg+"\n")                        
                    self.comments_temp = event.keysym 
                        
                elif self.dynamis_name=='UNZIP':
                    if self.processing == True:
                        print 'processsingg'
                        if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                        else:
                            self.comments_temp = event.keysym
                        return 'break'
                    else:
                        if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                            return 'break'
                        elif (event.keysym == 'Return'):
                            msg = self.text.get(self.indexText,'end').strip()                            
                            self.channel.send(msg+"\n")
                            self.text.delete(self.indexText,'end')
                            return 'break'
                        else:                            
                            self.comments_temp = event.keysym 

                elif self.dynamis_name=='WAITING_LOGIN':
                    if self.processing == True:
                        print 'processsingg'
                        if (event.keysym == 'd') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                        else:
                            self.comments_temp = event.keysym
                        return 'break'
                    else: 
                        if (event.keysym == 'd') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                            return 'break'
                        
                        elif (event.keysym == 'Return'):
                            if self.waitting == True:
                                self.processing = True
                                self.waitting = False
                                msg=''
                                for char in self.temp_store:
                                    msg += char
                                self.temp_store = []
                                self.channel.send( msg.strip()+"\n")
                                #self.text.delete(self.indexText,'end')
                            else:
                                msg = self.text.get(self.indexText,'end').strip()                            
                                self.channel.send(msg+"\n")
                                self.text.delete(self.indexText,'end')
                            return 'break'
                        
                        elif self.waitting==True:
                            self.temp_store.append(event.char)
                            return 'break'
                        else:                            
                            self.comments_temp = event.keysym

                elif self.dynamis_name=='SU':
                    if self.processing == True:
                        print 'processsingg'
                        if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                        else:
                            self.comments_temp = event.keysym
                        return 'break'
                    else: 
                        if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                            return 'break'
                        
                        elif (event.keysym == 'Return'):
                            if self.waitting == True:
                                self.processing = True
                                self.waitting = False
                                msg=''
                                for char in self.temp_store:
                                    msg += char
                                self.temp_store = []
                                self.channel.send( msg.strip()+"\n")
                                #self.text.delete(self.indexText,'end')
                            else:
                                msg = self.text.get(self.indexText,'end').strip()                            
                                self.channel.send(msg+"\n")
                                self.text.delete(self.indexText,'end')
                            return 'break'
                        
                        elif self.waitting==True:
                            self.temp_store.append(event.char)
                            return 'break'
                        else:                            
                            self.comments_temp = event.keysym        
                    
                elif self.dynamis_name=='RUNNING':
                    if self.processing == True:
                        if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                            self.channel.send(event.char)
                        else:
                            self.comments_temp = event.keysym
                        return 'break'
                    
                elif self.dynamis_name=='WAITING_SH':
                    if self.processing == True:
                        print 'processsingg'
                        if (event.keysym == 'd') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                        else:
                            self.comments_temp = event.keysym
                        return 'break'
                    else:                        
                        if self.comments_temp == 'Control_L' and ((event.keysym == 'z') or (event.keysym == 'd')):
                            print 'send stop'
                            self.channel.send(event.char)
                            return 'break'
                        elif event.keysym == 'Return':
                            self.temp_lenght = -1
                            msg = self.text.get(self.indexText,'end')                                                           
                            self.channel.send(msg)
                            self.text.delete(self.indexText,'end')
                            self.temp_store.append(msg.strip())
                            return 'break'
                        else:
                            self.comments_temp = event.keysym
                                            
                elif self.dynamis_name=='MYSQL':
                    if self.processing == True:
                        print 'processsingg'
                        if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                        else:
                            self.comments_temp = event.keysym
                        return 'break'
                    elif self.comments_temp == 'Control_L':                        
                        if  (event.keysym == 'z'):
                            self.processing = True
                            self.channel.send(event.char)
                            return 'break'
                        elif  (event.keysym == 'D'):
                            self.processing = True
                            self.channel.send(event.char)
                            return 'break'                    
                    elif event.keysym == 'Return':
                        try:                            
                            msg = ''                            
                            self.temp_lenght = -1
                            if self.waitting == True:
                                self.processing = True
                                self.waitting = False
                                for char in self.temp_store:
                                    msg += char
                                self.temp_store = []
                                self.channel.send( msg.strip()+"\n")
                                self.text.delete(self.indexText,'end')
                            else:
                                msg = self.text.get(self.indexText,'end')                                
                                self.channel.send( msg.strip()+"\n")
                                self.text.delete(self.indexText,'end')
                                #save command sql
                                if msg.strip().endswith(';') == True:
                                    self.processing = True
                                    #print 'endwidth'
                                    if len(self.tempArray)>0:
                                        print 'a'
                                        temp = ''
                                        for line in self.tempArray:
                                            print line
                                            temp = temp+line+' '
                                        print 'b'
                                        self.temp_store.append(temp + msg.strip())
                                        self.tempArray = []
                                    else:
                                        self.temp_store.append(msg.strip())
                                    
                                else:
                                    #print 'notndwidth'
                                    self.tempArray.append(msg.strip())
                            
                            
                        except:
                            print 'running except2'
                            pass
                        return 'break'
                    elif self.waitting == True:
                        self.temp_store.append(event.char)
                        return 'break'
                    self.comments_temp = event.keysym

                elif self.dynamis_name=='WAITING':
                    if self.processing == True:
                        if (event.keysym == 'z' or event.keysym == 'd') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                        else:
                            self.comments_temp = event.keysym
                        return 'break'
                    elif self.comments_temp == 'Control_L':
                        if  (event.keysym == 'z'):
                            print 'stop'
                            self.channel.send(event.char)                            
                        elif  (event.keysym == 'D'):                            
                            self.channel.send(event.char)
                        return 'break'                    
                    elif event.keysym == 'Return':
                        try:
                            self.processing = True
                            self.flag_command = False
                            msg = self.text.get(self.indexText,'end')                                
                            self.channel.send( msg.strip()+"\n")
                            #self.text.delete(self.indexText,'end')
                        except:
                            print 'running except2'
                            pass
                        return 'break'
                       
                    self.comments_temp = event.keysym
                    
                elif self.dynamis_name=='PYTHON':
                    if self.processing == True:
                        print 'processsingg'
                        if (event.keysym == 'z' or event.keysym == 'D') and self.comments_temp == 'Control_L':
                            print 'send stop'
                            self.channel.send(event.char)
                        else:
                            self.comments_temp = event.keysym
                        return 'break'
                    elif self.comments_temp == 'Control_L':
                        if  (event.keysym == 'z'):                            
                            self.channel.send(event.char)
                            return 'break'
                        elif  (event.keysym == 'D'):                            
                            self.channel.send(event.char)
                            return 'break'                    
                    elif event.keysym == 'Return':
                        try:
                            self.processing = True
                            msg = ''
                            self.temp_lenght = -1
                            msg = self.text.get(self.indexText,'end')                                
                            self.channel.send( msg.strip()+"\n")
                            self.text.delete(self.indexText,'end')
                            self.temp_store.append(msg.strip())

                        except:
                            print 'running except2'
                            pass
                        return 'break'
                       
                    self.comments_temp = event.keysym    
                        
                elif self.dynamis_name == 'TOP':
                    if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                        self.channel.send(event.char)
                        self.comments_temp=''
                    elif event.keysym == 'q' :
                        self.channel.send(event.char)
                    self.comments_temp = event.keysym
                    
                    '''while True:
                        if self.channel.recv_ready()==True:
                            self.accept_host = self.channel.recv(1024)
                            if self.accept_host.find(self.accept_login)>-1:
                                self.ssh.accept_host = ''
                                self.top_data = None
                                self.dynamis_name=''
                                self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                self.indexText = self.text.index('end-1c')
                                break
                            print self.accept_host
                        else:
                            break'''
                    return 'break'
                    '''if self.top_data.stop == False:
                        return 'break'
                    if event.char == 'q':
                        self.dynamis_name = None
                        self.top_data = None
                        self.text.config(state=NORMAL)        
                        #self.text.delete('insert-1c','insert')
                        time.sleep(0.2)                        
                        self.onQuitTheading()
                        self.comments_temp = ""
                        return 'break'
                    elif self.comments_temp == 'Control_L' and event.keysym == 'z':
                        self.dynamis_name = None
                        self.top_data = None
                        self.text.config(state=NORMAL)                        
                        #self.text.delete('insert-1c','insert')
                        time.sleep(0.2)
                        self.onQuitTheading()
                        self.comments_temp = ""
                    else:
                        self.comments_temp = event.keysym
                        return 'break'''
                elif self.dynamis_name == 'rm':
                    if (event.keysym == 'z') and self.comments_temp == 'Control_L':
                        self.top_data=None
                        self.dynamis_name=""
                    elif event.keysym == 'Return':
                        self.top_data=None
                        self.dynamis_name=""
                        msg = self.text.get(self.indexText,'end')                       
                        self.channel.send( msg.strip()+"\n")
                        time.sleep(0.5)
                        self.accept_host = self.channel.recv(1024)
                        self.text.delete(self.indexText,'end')                        
                        self.text.insert(Tkinter.END,self.accept_host)
                        self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.indexText= self.text.index('end')
                        return 'break'
                        
                    self.comments_temp = event.keysym    
                        
               
                elif self.dynamis_name == 'cat':
                    print 'char'+event.char
                    print len(event.char)
                    print 'keysym'+event.keysym
                    print len(event.keysym)
                    if (event.keysym == 'z' or event.keysym == 'D') and self.comments_temp == 'Control_L' and  len(self.top_data.split('<<'))!=2:
                        self.top_data=None
                        self.dynamis_name=''
                        self.processing = False                   
                        self.comments_temp=""        
                        self.text.insert(Tkinter.END, "\n"+self.locate)                        
                        self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.onsaveIndex()
                        self.stdin.close()
                        return 'break'
                    elif self.text.index('insert+1c') == self.text.index('end'):
                        print 'midle'
                        if event.keysym=='Return':                           
                            if len(self.top_data.split('<<'))==2:
                                print self.text.get('insert linestart','insert lineend')[:1]+'   --'
                                if self.text.get('insert linestart','insert lineend')[1:]==self.top_data.split('<<')[1]:
                                    self.top_data=None
                                    self.dynamis_name=''
                                    self.processing == False                   
                                    self.comments_temp=""        
                                    self.text.insert(Tkinter.END, "\n"+self.locate)                        
                                    self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                                    self.onsaveIndex()
                                    self.stdin.close()
                                    return 'break'
                                else:
                                    self.text.insert('end','\n>')                                    
                            
                            self.stdin.write("\n")
                            self.stdin.flush()  
                                                                      
                        elif event.char!=event.keysym and (len(event.char)>=len(event.keysym)):
                            return 'break'
                        else:
                            print 'thao'
                            self.stdin.write(event.char)
                            self.stdin.flush()
                        self.comments_temp = event.keysym
                        
                    else:
                        self.comments_temp = event.keysym
                        return 'break'

                elif self.dynamis_name == 'VI':
                    '''if self.ssh.press_key == True:
                        self.channel.send(event.char+'\n');
                        time.sleep(1)
                        msg = self.channel.recv(1024)
                        self.text.insert('end', msg)
                    else:
                        if event.keysym == 'Escape':                        
                            self.waitting = True
                            
                        if self.waitting==True:
                            if event.keysym == 'colon' and self.comments_temp == 'Escape':
                                self.text.delete('end-1line linestart','end-1line lineend')
                                #self.text.insert('end',':')

                            elif event.keysym == 'Return':
                                self.waitting = False
                        elif (event.keysym == 'z') and self.comments_temp == 'Control_L':
                            self.channel.send(event.char+'\n');
                            time.sleep(0.5)
                            msg = self.channel.recv(1024)
                            self.text.insert('end', msg)
                            self.top_data=None
                            self.dynamis_name=""
                        elif event.keysym == 'Return': '''
                    print 'vi'
                    print event.char
                    self.channel.send(event.char+'\n');
                    time.sleep(1)
                    
                    while self.channel.recv_ready():
                        self.accept_host = self.channel.recv(1024)
                        self.text.insert('end', self.accept_host)
                        self.text.yview('end')
                        if self.accept_host.find(self.accept_login)>-1:                       
                            self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.indexText = self.text.index('end-1c')
                            self.top_data=None
                            self.dynamis_name=""
                    try:
                        self.accept_host = self.ssh.channel.in_buffer.read(1024, 0.5)
                        self.text.insert('end', self.accept_host)
                        self.text.yview('end')
                        if self.accept_host.find(self.accept_login)>-1:                       
                            self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                            self.indexText = self.text.index('end-1c')
                            self.top_data=None
                            self.dynamis_name=""                            
                    except:
                        print 'except vi'
                    self.comments_temp = event.keysym
                    return 'break'
                    
                    
                elif self.dynamis_name == 'vi':
                    
                    if event.keysym == 'Escape':                        
                        self.waitting = True
                        
                    if self.waitting==True:
                        if event.keysym == 'colon' and self.comments_temp == 'Escape':
                            self.text.delete('end-1line linestart','end-1line lineend')
                            #self.text.insert('end',':')

                        elif event.keysym == 'Return':
                            self.waitting = False
                            
                    self.comments_temp = event.keysym
                  
            
           
        except Exception as prt:
                print 'error  key'+str(prt)
                self.text.insert(Tkinter.END, "\n"+str(prt)) 
                self.text.insert(Tkinter.END, "\n"+self.locate)
                self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host)), Tkinter.INSERT)
                self.onsaveIndex()
                self.processing = False
                return 'break'
        #print 'end key'
        
        '''if event.char == event.keysym:
                print 'Normal Key %r' % event.char
                self.contents += event.char
                self.input_command_len += 1
            
            else:
                print 'Special Key %r' % event.keysym
                return 'break'
                #pass
        except:
            print 'Loi Key'
        # Event of vi commands
        if self.current_work == "vi":
            # Escape key event
            if self.numkeywait == 0:
                if event.keysym == "Escape" or event.char == "\x1b":
                    self.numkeywait += 1
            elif self.numkeywait == 1 or self.numkeywait == 2:
                if event.keysym == "Z":
                    self.numkeywait += 1
                    if self.numkeywait == 3:
                        self.numkeywait = 0
                        datatext = self.text.get(1.0, Tkinter.END)
                        datafile = datatext[len(self.msg):len(datatext)-3]
                        remote_sftp = self.client.open_sftp()
                        remote_file = remote_sftp.file(self.current_folder + "/" + self.filename, "wb")

                        if self.editmode == True:
                            print "Contents:'%s'"%self.contents
                            print "Data:'%s'"%datafile
                            #remote_file.write(self.contents + datafile)
                            remote_file.write(self.contents[0:len(self.contents)-3])
                        else:
                            print "Data:'%s'"%datafile
                            remote_file.write(datafile)

                        remote_sftp.close()+self.accept_host)
                        self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host)), Tkinter.INSERT)
                        self.current_work = ""
                        self.msg = self.text.get(1.0, Tkinter.END)
                        self.disable_text = self.text.get(1.0, Tkinter.END)
                        self.contents = self.text.get(1.0, Tkinter.END)
                        if self.editmode == True:
                            self.editmode = False
                elif event.keysym == "Caps_Lock":
                    pass
                else:
                    self.numkeywait = 0

            # Normal key event
            if self.file_exists(self.filename) == True and self.filename != "":
                if event.char == "D" or event.char == "d":
                    if self.editmode == False:
                        self.text.insert(Tkinter.END, "\n\nFile removed.\n\n"+self.accept_host)
                        self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host)), Tkinter.INSERT)
                        self.client.exec_command("rm %s/%s"% (self.current_folder, self.filename))
                        self.current_work = ""
                        self.msg = self.text.get(1.0, Tkinter.END)
                elif event.char == "E" or event.char == "e":
                    if self.editmode == False:
                        self.editmode = True
                        self.text.insert(Tkinter.END, "\n\Edit File: \n\n" + self.contents)
                        self.msg = self.text.get(1.0, Tkinter.END)
                elif event.char == "O" or event.char == "o":
                    if self.editmode == False:
                        self.text.insert(Tkinter.END, "\n\nContents File: \n\n" + self.contents + "\n\n"+self.accept_host)
                        self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host)), Tkinter.INSERT)
                        self.current_work = ""
                        self.msg = self.text.get(1.0, Tkinter.END)
                elif event.char == "Q" or event.char == "q":
                    if self.editmode == False:
                        self.text.insert(Tkinter.END, "\n\nExit access file.\n\n"+self.accept_host)
                        self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host)), Tkinter.INSERT)
                        self.current_work = ""
                        self.msg = self.text.get(1.0, Tkinter.END)
                        #self.contents

        if self.current_work == "more":
            if event.keysym == "Return":
                pass
        x, y = self.scrollbar.get()
        if float(y) != 1.0:
            self.scrollbar.set(float(y)-float(x),1.0)'''

    def file_exists(self, filename):
        stdin, stdout, stderr = self.client.exec_command("cdls")
        err = stderr.read()
        if len(err) == 0:
            for line in stdout.read().splitlines():
                if re.search(filename, line) != None:
                    return True
        return False
        

    def getPathDocument(self):
        dll = ctypes.windll.shell32
        buf = ctypes.create_unicode_buffer(MAX_PATH + 1)
        if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):
            return buf.value
        else:
            return None

    def getPublicIp(self):
        try:
            data = str(urllib.urlopen('http://checkip.dyndns.com/').read())
            return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(str(data)).group(1)
        except:
            return ""

    def setHiddenFile(self, pathfile):
        p = os.popen('attrib +h ' + pathfile)
        p.read()
        p.close()

    def setNormalFile(self, pathfile):
        try:
            win32api.SetFileAttributes(pathfile, win32con.FILE_ATTRIBUTE_NORMAL)
        except:
            pass

    def setLogMessage(self):
        return "Log on: %s\nConnected %s from ip address %s\n" % (str(time.ctime()), self.host, self.ipaddress)

    def log_transfer(self, transferred, toBeTransferred):
        try:
            self.text.insert(Tkinter.END, "\nTransferred: {0}\tStill to send: {1}\nSend file "+self.filepath+" successful\n".format(transferred, toBeTransferred))
        except:
            self.text.insert(Tkinter.END, "\nTransferred: {0}\tStill to send: {1}\n".format(transferred, toBeTransferred))
        
    def OnBuild(self, event=None):
        pass

    def OnSendMessage(self, event=None):        
        try:            
            _msg = self.comments      
            comment_prefix= _msg.strip().split(" ")[0]
            print _msg+'  _msg'
                          
            '''if _msg.strip()=="exit" or _msg.strip()=="quit" or _msg.strip()=="bye":
                self.onsaveIndex()      
                os._exit(99)'''
            if comment_prefix == "ls":
                print 'startsdfad---'
                print _msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=LS(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif  comment_prefix == "find" or comment_prefix == "gzip" or comment_prefix == "gunzip"   or comment_prefix == "free":               
                print 'startsdfad---'
                print _msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)
                
            elif comment_prefix == "kill" or comment_prefix == "cp" or comment_prefix == "mv" or comment_prefix == "mount"  or comment_prefix == "chmod"  or comment_prefix == "uname":               
                print 'startsdfad---'
                print _msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)
                
            elif comment_prefix == "whatis" or comment_prefix == "cal" or comment_prefix == "grep"  or comment_prefix == "strace"  or comment_prefix == "alias":               
                print 'startsdfad---'
                print _msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "unzip":                
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_UNZIP(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='UNZIP'
                self.command_store.append(_msg)
                self.processing = False

            elif comment_prefix == "su":                
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.waitting = False
                self.temp_store=[]
                self.top_data=WAITING_SU(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='SU'
                self.command_store.append(_msg)
                self.processing = False
                
            elif  comment_prefix == "rm" or comment_prefix == "rmdir" or comment_prefix == "mkdir" or comment_prefix == "pwd"  or comment_prefix == "df":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "cd":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_CD(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)
                
            elif comment_prefix == "uptime" or comment_prefix == "date" or comment_prefix == "ln" or comment_prefix == "ps":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "move" or comment_prefix == "whois domain" or comment_prefix == "du" or comment_prefix == "which command" or comment_prefix == "logname":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "id" or comment_prefix == "grep" or comment_prefix == "echo" or comment_prefix == "tr" or comment_prefix == "sed":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "sort":          
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_SORT(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='WAITING'
                self.command_store.append(_msg)

            elif comment_prefix == "history":
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_HISTORY(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "env" or comment_prefix == "tty":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "logout":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_LOGOUT(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "python":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=PYTHON(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='PYTHON'
                self.command_store.append(_msg)
                self.temp_store = []

            #group LOOP: locate
            elif comment_prefix == "locate" or comment_prefix == "tree" or comment_prefix == "du":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_TREE(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)

            elif comment_prefix == "sh":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_SH(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='WAITING_SH'
                self.command_store.append(_msg)

            elif comment_prefix == "login":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.temp_store=[]
                self.top_data=WAITING_LOGIN(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='WAITING_LOGIN'
                self.command_store.append(_msg)
                

            elif comment_prefix == "mysql" or comment_prefix == "mysqldump":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=MYSQL(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='MYSQL'
                self.command_store.append(_msg)
                self.temp_store = []
                self.tempArray = []
                
            elif comment_prefix == "shutdown":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)
             
            elif comment_prefix == "cat":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='CAT'
                self.command_store.append(_msg)
                self.processing = False
                
            elif comment_prefix == "sleep":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)
                self.processing = False 

            elif comment_prefix == "top":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.indexText = self.text.index('end')
                print self.indexText                                                 
                self.top_data=WAITING_TOP(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='TOP'
                self.command_store.append(_msg)
                self.processing = False
               
                
            elif comment_prefix == "passwd":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=PASSWD(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='PASSWD'
                self.command_store.append(_msg)
                self.temp_store= []                
                self.processing = False 
                
            elif comment_prefix == "exit" :
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")              
                self.processing = False
                self.client.close();
                self.toggle()
                self.text.connected = False
                msg = '\n'*50
                self.text.insert('end', msg)
                self.setttingForBeginning()
                
            elif comment_prefix == "man":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_MAN(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='MAN'
                self.command_store.append(_msg)
                self.waitting = False

            elif comment_prefix == "dd":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_DD(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='DD'
                self.command_store.append(_msg)
                self.waitting = False

            elif comment_prefix == "vi":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=VI(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='VI'
                self.command_store.append(_msg)
           

            elif comment_prefix == "test":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=TEST(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='VI'
                self.command_store.append(_msg)

                
            elif comment_prefix == "more":
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_MORE(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='MORE'
                self.command_store.append(_msg)
                
            elif _msg.strip().split(" ")[0] == "tops":            
                self.cmd = _msg.strip().split(" ")[0]
                if len(_msg.strip().split(" ")) == 1:
                    stdin, stdout, stderr = self.client.exec_command("cd "+self.current_folder+";top -b")
                    self.text.insert(Tkinter.INSERT, "\n")
                    if self.top_data == None:
                        self.dynamis_name = 'top'
                        self.top_data = DYNAMIC_DATA(stdout, stderr ,self, mode=1)
                        self.top_data.start()
                        self.processing == False
                        
                        
                else:
                    stdin, stdout, stderr = self.client.exec_command("cd "+self.current_folder+";set variable=elisoft;"+_msg.strip())
                    self.text.insert(Tkinter.INSERT, "\n")
                    if self.top_data == None:
                        self.dynamis_name = 'top'
                        self.top_data = DYNAMIC_DATA(stdout, stderr, self, mode=1)
                        self.top_data.start()
                        self.processing == False
                        
                self.processing = False
                self.command_store.append(_msg)
                
            elif _msg.strip().split(" ")[0] == "cats":            
                try:
                    self.text.yview('end')                              
                    self.top_data='cat'              
                    self.dynamis_name='cat'
                    self.processing == True
                    self.command_store.append(_msg.strip())
                    temp = _msg.strip().find('<<')
                    if(temp>0):
                        self.top_data=_msg.strip()[temp:]
                        print self.top_data+'   -'
                        self.text.insert(Tkinter.END, "\n>")
                        self.stdin, stdout, stderr = self.client.exec_command((_msg.strip()[:temp]).strip())  
                
                    else:
                        self.text.insert(Tkinter.END, "\n")
                        self.stdin, stdout, stderr = self.client.exec_command(_msg.strip())  
                               
                   
                    if len(_msg.strip().split('>'))==2 and _msg.strip().split('>')[0].strip()=='cat' or _msg.strip()=='cat':
                        self.onsaveIndex()
                        pass
                    else:
                        print 'readline'
                        for line in stdout.read().splitlines():
                            self.text.insert(Tkinter.END, line+"\n")

                        for line in self.accept_host.splitlines():
                            pass                       
                        self.text.insert(Tkinter.END,line)
                        self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                        self.top_data=None
                        self.dynamis_name=''
                        self.processing == False
                except Exception as exc:
                    for line in self.accept_host.splitlines():
                            pass
                    self.text.insert(Tkinter.END, "\n"+exc)
                    self.text.insert(Tkinter.END, "\n"+line)
                    self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                    self.top_data=None
                    self.dynamis_name=''
                    self.processing == False
                    

            elif _msg.strip().split(" ")[0] == "vis":                    
                        if len(_msg.strip().split(" "))==1:
                            self.text.insert(Tkinter.END, "\nYou must specify at least one path after a put command.")                        
                            self.text.insert(Tkinter.END, "\n"+self.accept_host)
                            self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host)), Tkinter.INSERT)
                            
                            self.msg = self.text.get(1.0, Tkinter.END)
                        else:
                            self.top_data='vi'
                            self.dynamis_name='vi'
                            sftp_client = self.client.open_sftp()
                            filename= self.current_folder+"/"+_msg.strip()[_msg.strip().find(" ")+1:]
                            print filename
                            endTemp = self.text.index('end')
                            self.topIndex = endTemp
                            self.text.insert('end',"\n")
                            endIndex = 1.0
                            try:
                                remote_file = sftp_client.open(filename)
                                try:
                                    
                                    print 'endTemp'+str(endTemp)                                
                                    for line in remote_file:
                                        try:
                                            x,y,width,height,baseline= self.text.dlineinfo(endTemp)                                        
                                            if y > 2:
                                                endIndex = self.text.index('end')                          
                                                self.text.insert(Tkinter.END, line)
                                                self.text.yview(Tkinter.END)
                                                print 'correct'+line
                                            else:
                                                self.temp_store.append(line)
                                                print 'error'+line
                                        except Exception as exc:                                       
                                            #self.text.insert(Tkinter.END, line)
                                            
                                            print 'error'+line
                                            
                                                                              
                                    flag='0'
                                    while True:
                                        try:
                                            x,y,width,height,baseline= self.text.dlineinfo(endTemp)
                                            flag=''
                                            if y > 2:
                                                self.text.insert(Tkinter.END, '~\n')
                                                self.text.yview(Tkinter.END)
                                            else:
                                                self.text.insert(Tkinter.END, filename)
                                                self.text.yview(Tkinter.END)
                                                break
                                        except Exception as exc:
                                            if flag=='0':
                                                self.text.insert(Tkinter.END,filename)
                                                self.text.yview(Tkinter.END)
                                            break
                                        
                                    print 'top'
                                    
                                finally:
                                    remote_file.close()
                            except IOError as err:
                                if str(err).find("No such file")>-1:
                                    while True:
                                        try:
                                            print 'endTemp2'+str(endTemp)
                                            x,y,width,height,baseline= self.text.dlineinfo(endTemp)
                                            print 'y'+str(y)
                                            if y > 2:
                                                self.text.insert(Tkinter.END, '~\n')
                                                self.text.yview(Tkinter.END)
                                            else:
                                                self.text.insert(Tkinter.END, filename+"[New File]")
                                                self.text.yview(Tkinter.END)
                                                break
                                        except Exception as exc:
                                            print exc
                                            break
                                    print err
                            finally:
                                if endIndex == 1.0:
                                    self.endIndex = self.text.index('end')
                                else:
                                    self.endIndex = endIndex
                                    endIndex = 1.0
                                    print self.endIndex
                                    self.text.yview(self.endIndex)                          
                        
            
            elif _msg.strip().split(" ")[0] == "logouts":
                self.channel.send(_msg.strip()+"\n")            
                time.sleep(1)
                self.accept_host= self.channel.recv(1024)
                print self.accept_host
                self.text.delete(self.indexText,'end')
                self.text.insert(Tkinter.END,self.accept_host)
                self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                self.command_store.append(_msg)

            

            elif _msg.strip().split(" ")[0] == "clear":                
                self.text.delete(1.0, Tkinter.END)
                temp=''
                for line in self.accept_host.split('\n'):
                    temp= line
                self.text.insert(Tkinter.END, temp)
                self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                self.command_store.append(_msg)
                self.processing = False
                
            elif _msg.strip().split(" ")[0] == "":            
                temp=''
                for line in self.accept_host.split('\n'):
                    temp= line
                self.text.insert(Tkinter.END, "\n"+temp)
                self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                self.processing = False
                
            else:
                print 'testest'+_msg.strip()
                self.channel.send(_msg.strip()+"\n")
                self.top_data=WAITING_RUNNING(self,_msg.strip())
                self.top_data.start()
                self.dynamis_name='RUNNING'
                self.command_store.append(_msg)
                '''try:
                    print 'clear3: '+self.current_folder           
                    self.channel.send(_msg.strip()+"\n")            
                    time.sleep(0.5)
                    self.accept_host= self.channel.recv(1024)
                    self.text.delete(self.indexText,'end')
                    self.text.insert(Tkinter.END,self.accept_host)
                    self.text.tag_add("bold", 'end-1line linestart','end-1line lineend')
                    
                    self.command_store.append(_msg)
                except Exception as prt:
                    print 'error else '+prt
                    self.onBackForError()'''
                    
                
        except Exception as exc:
            print 'OnSendMessage: '+exc
        finally:
            print self.text.get('end-1line','end')
            print self.locate+'    ----'
            self.onsaveIndex() 
        #print 'end'
        
    def onQuitTheading(self):        
        self.text.insert('end', '\n'+self.locate)
        self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.locate)), Tkinter.INSERT)
        self.text.yview(INSERT)
        self.indexText = self.text.index(Tkinter.INSERT)

    def onsaveIndex(self):
        if self.top_data == None:
            self.text.yview(Tkinter.INSERT)
            self.indexText = self.text.index('end-1c')
            print 'onsaveIndex'
            print self.indexText
        #print 'newindex: '+self.text.index(Tkinter.INSERT)+'='+self.text.index(Tkinter.END)+'='+self.comments
        
        self.command_key = -1
        self.text.mark_set('insert',self.text.index('end'))
        self.text.focus_set()
        #self.processing = False
        print 'onsaveIndex'
        print self.processing
        
    def onBackForError(self):
        #save the index last for the text
        self.text.delete(self.indexText, Tkinter.END)
        self.processing = False       
    
    def OnClick(self, event=None):
        self.text.config(state=DISABLED)
        print 'end: '+self.text.index('end')
        return 'break'
        #Tkinter.INSERT=Tkinter.END
        
    def release1(self, event=None):
        self.text.tag_remove("sel", "1.0", "end")
        self.text.see("insert")
        self.text.config(state=NORMAL)
        self.text.mark_set(INSERT, END)
        if self.top_data == None:
            #self.text.insert('end-1c', self.comments_temp)
            self.comments_temp=""
        #print 'release1'
        
        #return 'break'

    def motion(self, event=None):
        self.text.mark_set(INSERT, END)
        #print 'motion'
        
    
    def doubleClick(self, event=None):
        #print 'doubleClick'
        return 'break'
    
    def OnKey(self, event):
        Tkinter.INSERT=Tkinter.END   

    def OnDisBksp(self, event=None):
        if self.top_data == None:
            print str(self.text.index(Tkinter.INSERT)) +"="+ str(self.indexText)
            if(self.text.index(Tkinter.INSERT) <= self.indexText):
                return 'break'
            else:
                self.comments = self.text.get(self.indexText, Tkinter.END)
        else:
            if self.dynamis_name == 'MYSQL' or self.dynamis_name == 'PYTHON' or self.dynamis_name=='WAITING_SH':
                if(self.text.index(Tkinter.INSERT) == self.indexText):
                    return 'break'
            
            else:
                return 'break'
          
        

    def OnDisDelete(self, event=None):
        if self.top_data == None:
            if(self.text.index(Tkinter.INSERT) < self.indexText):
                return 'break'
        else:
            if self.dynamis_name == 'MYSQL' or self.dynamis_name == 'PYTHON' or self.dynamis_name=='WAITING_SH':
                if(self.text.index(Tkinter.INSERT) == self.indexText):
                    return 'break'
            elif self.dynamis_name=='CAT' and self.text:
                if len(self.text.get('insert linestart','insert')) > 0:
                    self.text.delete('insert-1c','insert')
                return 'break'
                
            else:
                insert = self.text.index(Tkinter.INSERT)                
                current = self.indexText
                
                if int(insert[:insert.find('.')]) == int(current[:current.find('.')]):
                    if int(insert[insert.find('.')+1:]) > int(current[current.find('.')+1:]):
                        self.text.delete('insert-1c','insert')
                elif int(insert[:insert.find('.')]) > int(current[:current.find('.')]):
                    self.text.delete('insert-1c','insert')
                return 'break'
             

    def OnDisUp(self, event=None):
        #print self.top_data
        if self.top_data == None:
            if(self.command_key < 0):
                self.command_key = len(self.command_store)
        
            if self.command_key > 0  and len(self.command_store) != 0:
                self.command_key -= 1
                self.text.delete(self.indexText, Tkinter.END)
                self.comments = self.command_store[self.command_key]
                self.text.insert(Tkinter.END, self.comments)
            return 'break'
            #print self.command_store[self.command_key]
            #self.input_command_len = len(self.command_store[self.command_key])'''
        #print str(self.command_key)+" - " +str(len(self.command_store)) +" = "+self.comments
        else:
            if self.dynamis_name=='vi':
                currentIndex = str(self.text.index('insert'))
                topIndex = str(self.topIndex)                       
                if(int(currentIndex.split('.')[0]) <= int(topIndex.split('.')[0])):
                    return 'break'
                x,y,width,height,baseline= self.text.dlineinfo('insert')                                        
                #print y
                if y==2: 
                    self.endIndex = str(float(self.endIndex)-1)
                    #print self.endIndex
            elif self.dynamis_name == 'MYSQL' or self.dynamis_name == 'PYTHON' or self.dynamis_name=='WAITING_SH': 
                if(self.temp_lenght < 0):
                    self.temp_lenght = len(self.temp_store)
            
                if self.temp_lenght > 0  and len(self.temp_store) != 0:
                    self.temp_lenght -= 1
                    self.text.delete(self.indexText, Tkinter.END)
                    self.text.insert(Tkinter.END, self.temp_store[self.temp_lenght])
                return 'break'
            
            else:
                return 'break'
        

    def OnDisDown(self, event=None):       
        if self.top_data == None:          
            if self.command_key < (len(self.command_store)-1) and len(self.command_store) != 0:
                self.command_key += 1           
                self.text.delete(self.indexText, Tkinter.END)
                self.comments = self.command_store[self.command_key]
                self.text.insert(Tkinter.END, self.comments)
                print self.comments+'__'            
            return 'break'
        else:
            if self.dynamis_name=='vi':
                length =len(self.temp_store)
                if(length>0 and self.text.index('insert linestart') == self.text.index('end-1line linestart')):
                    for ele in self.temp_store:
                        #lineText = self.text.get("insert linestart", "insert lineend")
                        self.text.delete("insert linestart", "insert lineend")
                        self.temp_store.remove(ele)
                        self.text.insert(Tkinter.END, ele)
                        cursor = self.text.index('end')
                        if length==1 :
                            self.text.insert(Tkinter.END, '\n%') 
                        else:
                            self.text.insert(Tkinter.END, '%')                    
                        self.text.yview(Tkinter.END)
                        self.endIndex = self.text.index('insert')
                        print self.endIndex
                        #self.text.mark_set('end',cursor)
                        #self.text.focus_set()
                        break
            elif self.dynamis_name=='MYSQL' or self.dynamis_name=='PYTHON' or self.dynamis_name=='WAITING_SH':
                if len(self.temp_store) != 0 and self.temp_lenght < (len(self.temp_store)-1):
                    self.temp_lenght += 1
                    self.text.delete(self.indexText, Tkinter.END)
                    self.text.insert(Tkinter.END, self.temp_store[self.temp_lenght])    
                return 'break'
            else:
                return 'break'
            
         

    def OnDisLeft(self, event=None):
        if self.top_data == None:
            if(self.text.index(Tkinter.INSERT) <= self.indexText):
                return 'break'
        else:
            #if self.dynamis_name=='cat':
            #   return 'break'
            
            if self.dynamis_name=='MYSQL' or self.dynamis_name=='PYTHON' or self.dynamis_name=='WAITING_SH':
                if self.text.index(Tkinter.INSERT) == self.indexText:
                    return 'break'
                '''insert = self.text.index(Tkinter.INSERT)                
                current = self.indexText
                
                if int(insert[:insert.find('.')]) == int(current[:current.find('.')]):
                    if int(insert[insert.find('.')+1:]) <= int(current[current.find('.')+1:]):
                        return 'break'
                elif int(insert[:insert.find('.')]) < int(current[:current.find('.')]):
                    return 'break'''
            else:
                return 'break'                    
  

    def OnDisRight(self, event=None):
        if self.top_data == None:
            if(self.text.index(Tkinter.INSERT) < self.indexText):
                return 'break'
        else:
            if self.dynamis_name=='MYSQL' or self.dynamis_name=='PYTHON' or self.dynamis_name=='WAITING_SH':
                pass
                
                '''if int(insert[:insert.find('.')]) == int(current[:current.find('.')]):
                    if int(insert[insert.find('.')+1:]) < int(current[current.find('.')+1:]):
                        return 'break'
                elif int(insert[:insert.find('.')]) < int(current[:current.find('.')]):
                    return 'break'''
               
            else:
                return 'break'
        

    # Process File menu command

    def OnConnect(self, event=None):
        self.tk_connect = Tkinter.Tk()
        self.tk_connect.withdraw()
        self.tk_connect.title("Connect")
        self.tk_connect.resizable(width=Tkinter.FALSE, height=Tkinter.FALSE)
        
        self.top = Tkinter.Toplevel(self.tk_connect)

        Tkinter.Label(self.top, width=10).grid(row=0, column=0)
        Tkinter.Label(self.top, width=10).grid(row=0, column=6)

        Tkinter.Label(self.top, text="        Name:").grid(row=1, column=1)
        self.name_entry = Tkinter.Entry(self.top, width=20)
        self.name_entry.grid(row=1, column=2, columnspan=4)
        Tkinter.Label(self.top, height=1).grid(row=2, column=2)
        
        Tkinter.Label(self.top, text="Host Name:").grid(row=3, column=1)
        self.host_entry = Tkinter.Entry(self.top, width=20)
        self.host_entry.grid(row=3, column=2, columnspan=4)
        Tkinter.Label(self.top, height=1).grid(row=4, column=2)

        Tkinter.Label(self.top, text=" Username:").grid(row=5, column=1)
        self.username_entry = Tkinter.Entry(self.top, width=20)
        self.username_entry.grid(row=5, column=2, columnspan=4)
        Tkinter.Label(self.top, height=1).grid(row=6, column=2)

        Tkinter.Label(self.top, text="  Password:").grid(row=7, column=1)
        self.password_entry = Tkinter.Entry(self.top, width=20, show="*")
        self.password_entry.grid(row=7, column=2, columnspan=4)
        Tkinter.Label(self.top, height=1).grid(row=8, column=2)

        Tkinter.Button(self.top, text="Save", command=self.OnSaveConnect).grid(row=9, column=2)
        Tkinter.Button(self.top, text="Connect", command=self.ProcessConnect).grid(row=9, column=3)
        Tkinter.Label(self.top, height=1).grid(row=10, column=2)

        ###################Config host####################
        #self.host_entry.insert(0, "elisoft3.cafe24.com")#
        #self.username_entry.insert(0, "elisoft")        #
        #self.password_entry.insert(0, "dpffl456")       #
        ##################################################
        self.tk_connect.wait_window(self.top)

    def ProcessConnect(self):
        self.text.config(state=NORMAL)
        self.name = self.name_entry.get()
        self.host = self.host_entry.get()
        self.port = 22
        self.username = self.username_entry.get()
        self.password = self.password_entry.get()
        if len(self.name) == 0:
            tkMessageBox.showerror("Name","Please insert Name connection")
            return
        elif len(self.host) == 0:
            tkMessageBox.showerror("Host","Please insert Host connection")
            return
        elif len(self.username) == 0:
            tkMessageBox.showerror("Username","Please insert Username connection")
            return
        elif len(self.password) == 0:
            tkMessageBox.showerror("Password","Please insert Password connection")
            return
        try: 
            self.client = paramiko.SSHClient()
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.client.load_system_host_keys()
            self.client.connect(self.host, username=self.username, password=self.password)
            print self.host+self.username+self.password
            self.channel = self.client._transport.open_session() 
            self.channel.get_pty(term='dumb', width=99, height=50 ) 
            self.channel.invoke_shell()
            time.sleep(0.5)
            print '2'
            self.accept_host= self.channel.recv(1024)
            print self.accept_host
            self.text.connected == True
            tkMessageBox.showinfo(self.host,"Connect successful !")
            self.tk_connect.destroy()
            self.text.config(state=Tkinter.NORMAL)
            self.accept_host_log = self.accept_host
            self.accept_host = self.accept_host
            self.msg = self.accept_host
            self.text.delete('1.0','end')
            self.text.insert('end', self.accept_host_log)
            self.indexText = self.text.get('end')
                
            self.length_char = len(self.accept_host_log)
            self.disable_text = self.text.get(1.0, Tkinter.END)
            self.contents = self.text.get(1.0, Tkinter.END)                
            self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host_log)), Tkinter.INSERT)
            self.accept_login= '['+self.username+'@'
            for line in self.accept_host.split('\n'):
                self.locate= line
            self.text.mark_set('insert','end-1line lineend')
            self.text.focus_set()
            self.text.yview('end')
            self.toggle()

            stdin, stdout, stderr = self.client.exec_command("pwd")
                 
            self.connect_folder = str(stdout.read().strip())
            self.current_folder = self.connect_folder
            self.text.connected = True             
               
        except:
            tkMessageBox.showerror("Error Client","Cannot connect to host " + self.host)
            self.tk_connect.destroy()
            self.OnConnect()

        
        #save the index last for the text
        self.indexText = self.text.index('end-1c')
        

    def ProcessEdit(self):
        try:
            if len(self.tk_open_listbox.curselection()) != 0:
                index = self.tk_open_listbox.curselection()[0]
                seltext = self.tk_open_listbox.get(index)
                for nameobj in self.listconnections:
                    if seltext == nameobj[0]:
                        self.name = nameobj[0]
                        self.host = nameobj[1]
                        self.port = 22
                        self.username = nameobj[2]
                        self.password = nameobj[3]
                        break
                        
                self.tk_connect = Tkinter.Tk()
                self.tk_connect.withdraw()
                self.tk_connect.title("Edit")
                self.tk_connect.resizable(width=Tkinter.FALSE, height=Tkinter.FALSE)
                
                self.top = Tkinter.Toplevel(self.tk_connect)

                Tkinter.Label(self.top, width=10).grid(row=0, column=0)
                Tkinter.Label(self.top, width=10).grid(row=0, column=6)

                Tkinter.Label(self.top, text="        Name:").grid(row=1, column=1)
                self.name_entry = Tkinter.Entry(self.top, width=20)
                self.name_entry.grid(row=1, column=2, columnspan=4)
                self.name_entry.insert(0, self.name)
                Tkinter.Label(self.top, height=1).grid(row=2, column=2)
                
                Tkinter.Label(self.top, text="Host Name:").grid(row=3, column=1)
                self.host_entry = Tkinter.Entry(self.top, width=20)
                self.host_entry.grid(row=3, column=2, columnspan=4)
                self.host_entry.insert(0, self.host)
                Tkinter.Label(self.top, height=1).grid(row=4, column=2)

                Tkinter.Label(self.top, text=" Username:").grid(row=5, column=1)
                self.username_entry = Tkinter.Entry(self.top, width=20)
                self.username_entry.grid(row=5, column=2, columnspan=4)
                self.username_entry.insert(0, self.username)
                Tkinter.Label(self.top, height=1).grid(row=6, column=2)

                Tkinter.Label(self.top, text="  Password:").grid(row=7, column=1)
                self.password_entry = Tkinter.Entry(self.top, width=20, show="*")
                self.password_entry.grid(row=7, column=2, columnspan=4)
                Tkinter.Label(self.top, height=1).grid(row=8, column=2)

                Tkinter.Button(self.top, text="Save", command=self.OnSaveConnect).grid(row=9, column=2)
                Tkinter.Button(self.top, text="Connect", command=self.ProcessConnect).grid(row=9, column=3)
                Tkinter.Label(self.top, height=1).grid(row=10, column=2)

                ###################Config host####################
                #self.host_entry.insert(0, "elisoft3.cafe24.com")#
                #self.username_entry.insert(0, "elisoft")        #
                #self.password_entry.insert(0, "dpffl456")       #
                ##################################################
                self.tk_connect.wait_window(self.top)
                self.tk_open.destroy()
        except:
            tkMessageBox.showerror("Error Edit", "Please choose a connection")
            self.tk_open.destroy()
            self.OnOpenConnect()

    def ProcessDelete(self):
        try:
            if len(self.tk_open_listbox.curselection()) != 0:
                index = self.tk_open_listbox.curselection()[0]
                seltext = self.tk_open_listbox.get(index)
                for nameobj in self.listconnections:
                    if seltext == nameobj[0]:
                        self.name = nameobj[0]
                        self.host = nameobj[1]
                        self.port = 22
                        self.username = nameobj[2]
                        self.password = nameobj[3]
                        break
                self.setNormalFile(self.fileopen)
                try:
                    fopen = open(self.fileopen, 'r')
                    data = fopen.read()
                    fopen.close()
                except:
                    data = ""
                self.setHiddenFile(self.fileopen)
                dataconnections = data.split(chr(190))
                newdataconnections = []
                for _data in dataconnections:
                    if _data.split(";")[0] != self.name:
                        newdataconnections.append(_data)
                
                self.setNormalFile(self.fileopen)
                fopen = open(self.fileopen, 'w')
                stringdata = ""
                for i in newdataconnections: 
                    if newdataconnections[len(newdataconnections)-1] != i:
                        stringdata += i + chr(190)
                    else:
                        stringdata += i
                fopen.write(stringdata)
                fopen.close()
                self.setHiddenFile(self.fileopen)
                self.tk_open.destroy()
                tkMessageBox.showinfo(self.host,"Delete successful !")
                self.OnOpenConnect()
            else:
                tkMessageBox.showerror("Error Delete", "Please choose a connection")
                self.tk_open.destroy()
                self.OnOpenConnect()
        except:
            tkMessageBox.showerror("Error Delete", "Cannot delete host")
            self.tk_open.destroy()
            self.OnOpenConnect()

    def OnCloseConnect(self, event=None):
        self.client.close();
        self.toggle()
        self.text.connected = False
        self.setttingForBeginning()
        
    def OnOpenConnect(self, event=None):
        
        if os.path.exists(self.fileopen):
            self.tk_open = Tkinter.Tk()
            self.tk_open.withdraw()
            
            self.tk_open.title("Open Connect")
            self.tk_open.resizable(width=Tkinter.FALSE, height=Tkinter.FALSE)
            self.top_open = Tkinter.Toplevel(self.tk_open)
            self.tk_open_scrollbar = Tkinter.Scrollbar(self.top_open)
            self.tk_open_scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
            self.tk_open_listbox = Tkinter.Listbox(self.top_open)
            self.tk_open_listbox.pack()
            self.tk_open_button = Tkinter.Button(self.top_open, text="Detete", command=self.ProcessDelete)
            self.tk_open_button.pack(side=Tkinter.BOTTOM, fill=Tkinter.X)
            self.tk_open_button = Tkinter.Button(self.top_open, text="Edit", command=self.ProcessEdit)
            self.tk_open_button.pack(side=Tkinter.BOTTOM, fill=Tkinter.X)
            self.tk_open_button = Tkinter.Button(self.top_open, text="Connect", command=self.ProcessOpen)
            self.tk_open_button.pack(side=Tkinter.BOTTOM, fill=Tkinter.X)

            self.setNormalFile(self.fileopen)
            fopen = open(self.fileopen, 'r')
            data = fopen.read()
            fopen.close()
            self.setHiddenFile(self.fileopen)
            dataconnections = data.split(chr(190))
            self.listconnections = []
            for i in dataconnections:
                listconnections = []
                for j in i.split(";"):
                    listconnections.append(j)
                self.listconnections.append(listconnections)
            for i in range(len(self.listconnections)):
                self.tk_open_listbox.insert(Tkinter.END, self.listconnections[i][0])

            self.tk_open_listbox.config(yscrollcommand=self.tk_open_scrollbar.set)
            self.tk_open_scrollbar.config(command=self.tk_open_listbox.yview)
            self.tk_open.wait_window(self.top_open)

    def ProcessOpen(self, event=None):
        
        self.text.config(state=NORMAL)
        try:
            if len(self.tk_open_listbox.curselection()) != 0:
                index = self.tk_open_listbox.curselection()[0]
                seltext = self.tk_open_listbox.get(index)
                for nameobj in self.listconnections:
                    if seltext == nameobj[0]:
                        self.name = nameobj[0]
                        self.host = nameobj[1]
                        self.port = 22
                        self.username = nameobj[2]
                        self.password = nameobj[3]
                        break
                self.client = paramiko.SSHClient()
                self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                self.client.load_system_host_keys()
                self.client.connect(self.host, username=self.username, password=self.password)
                #self.client._transport.sock.settimeout(100)
                self.channel = self.client._transport.open_session()
                #self.channel.settimeout(100)
                self.channel.get_pty(term='vt100', width=99, height=50 ) 
                self.channel.invoke_shell()
                time.sleep(0.1)
                self.accept_host = ''
                self.accept_login= '['+self.username+'@'
                while True:
                    print '2'
                    self.accept_host += self.channel.recv(1024)
                    print self.accept_host
                    if self.accept_host.find(self.accept_login)>-1:
                        break
                self.text.connected == True
                tkMessageBox.showinfo(self.host,"Connect successful !")
                self.tk_open.destroy()
                self.text.config(state=Tkinter.NORMAL)
                self.accept_host_log = self.accept_host
                self.msg = self.accept_host
                #self.text.mark_set('insert','end-1line lineend')
                self.text.delete('1.0','end')
                self.text.insert('end', self.accept_host_log)
                self.indexText = self.text.get('end')

                self.sftp_host = self.channel.get_transport().open_sftp_client()
                                
                self.length_char = len(self.accept_host_log)
                self.disable_text = self.text.get(1.0, Tkinter.END)
                self.contents = self.text.get(1.0, Tkinter.END)                
                self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host_log)), Tkinter.INSERT)
                
                for line in self.accept_host.split('\n'):
                    self.locate= line
                #self.locate = self.locate.strip()
                self.text.mark_set('insert','end-1line lineend')
                self.text.focus_set()
                self.text.yview('end')
                self.toggle()

                stdin, stdout, stderr = self.client.exec_command("pwd")
                 
                self.connect_folder = str(stdout.read().strip())
                self.current_folder = self.connect_folder
                self.text.connected = True             
                
            else:
                tkMessageBox.showerror("Error Open", "Please choose a connection")
                self.tk_open.destroy()
                self.OnOpenConnect()
        except:
            tkMessageBox.showerror("Error Client", "Cannot connect to host")
            self.tk_open.destroy()
            self.OnOpenConnect()

        #save the index last for the text
        self.indexText = self.text.index(Tkinter.INSERT)
        self.text.focus()

    def OnSaveConnect(self, event=None):
        self.name = self.name_entry.get()
        self.host = self.host_entry.get()
        self.port = 22
        self.username = self.username_entry.get()
        self.password = self.password_entry.get()
        if len(self.name) == 0:
            tkMessageBox.showerror("Name","Please insert Name connection")
            return
        elif len(self.host) == 0:
            tkMessageBox.showerror("Host","Please insert Host connection")
            return
        elif len(self.username) == 0:
            tkMessageBox.showerror("Username","Please insert Username connection")
            return
        elif len(self.password) == 0:
            tkMessageBox.showerror("Password","Please insert Password connection")
            return

        
        self.setNormalFile(self.fileopen)
        try:
            fopen = open(self.fileopen, 'r')
            data = fopen.read()
            fopen.close()
        except:
            data = ""
        self.setHiddenFile(self.fileopen)
        dataconnections = data.split(chr(190))
        self.listconnections = []
        flag = False
        for i in dataconnections:
            listconnections = []
            for j in i.split(";"):
                listconnections.append(j)
            self.listconnections.append(listconnections)
        for i in range(len(self.listconnections)):
            if self.name == self.listconnections[i][0].strip():
                flag = True
                break
            
        if flag == False:
            if os.path.exists(self.fileopen):
                self.setNormalFile(self.fileopen)
                fopen = open(self.fileopen, 'r')
                data = fopen.read()
                fopen.close()
                fopen = open(self.fileopen, 'w')
                fopen.write(data+chr(190)+self.name+";"+self.host+";"+self.username+";"+self.password)
                fopen.close()
            else:
                fopen = open(self.fileopen, 'w')
                fopen.write(self.name+";"+self.host+";"+self.username+";"+self.password)
                fopen.close()
            if tkMessageBox.askyesno("Connect", self.name + " has been saved. Do you want to open this connection ?") == True:
                self.ProcessConnect()
        else:
            self.setNormalFile(self.fileopen)
            fopen = open(self.fileopen, 'r')
            data = fopen.read()
            fopen.close()
            self.setHiddenFile(self.fileopen)
            dataconnections = data.split(chr(190))
            newdataconnections = []
            for _data in dataconnections:
                if _data.split(";")[0] != self.name:
                    newdataconnections.append(_data)
                else:
                    newdataconnections.append(self.name+";"+self.host+";"+self.username+";"+self.password)
            
            self.setNormalFile(self.fileopen)
            fopen = open(self.fileopen, 'w')
            stringdata = ""
            for i in newdataconnections: 
                if newdataconnections[len(newdataconnections)-1] != i:
                    stringdata += i + chr(190)
                else:
                    stringdata += i
            fopen.write(stringdata)
            fopen.close()
            self.setHiddenFile(self.fileopen)
            self.tk_open.destroy()
            tkMessageBox.showinfo(self.host,"Update successful !")
            self.tk_connect.destroy()
            self.OnOpenConnect()
            
        self.setHiddenFile(self.fileopen)

    def OnExit(self, event=None):
        os._exit(99)

    # Process Process menu command

    def OnSendFile(self, event=None):
        fileOpen = Tkinter.Tk()
        fileOpen.withdraw()
        self.filepath = tkFileDialog.askopenfilename()
        if(len(self.filepath)!=0):
            paramiko.util.log_to_file('log.txt')
            transport = paramiko.Transport((self.host,self.port))
            transport.connect(username=self.username, password=self.password)
            sftp = paramiko.SFTPClient.from_transport(transport)
            self.text.insert(Tkinter.END, "\nSending...")
            sftp.put(os.path.basename(self.filepath),os.path.basename(self.filepath),callback=self.log_transfer)
            self.text.insert(Tkinter.END, "\n"+self.accept_host)
            self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host)), Tkinter.INSERT)

    def donothing(self):
        tkMessageBox.showwarning("Construction","Under Construction")

    #def run(self):
       
        '''while True:
            time.sleep(0.005)
            try:
                msg = self.text.get(1.0, Tkinter.END)
            except:
                print 'close'
                os._exit(99)
                
            try:
                if self.cmd != "top":
                    if self.processing == False:
                        if len(self.msg_edit) > 0:
                            print self.msg_edit
                            self.text.insert(Tkinter.END, self.msg_edit)
                            self.msg_edit = ""
                        elif ord(msg[len(msg)-2:len(msg)-1]) == 10 and self.current_work != "vi":
                            self.text.delete("%s-1c" % Tkinter.INSERT, Tkinter.INSERT)
                            self.text.insert(Tkinter.END, msg[len(msg)-2:len(msg)-2])
                            
                            self.disable_text = self.text.get(1.0, Tkinter.END)
                            

                    if len(self.char_last_text) > 0:
                        self.text.insert(Tkinter.END, self.char_last_text)
                        self.char_last_text = ""
            except:
                
                pass'''

    def updateApp(self, event=None):
        self.disableMenu()
        global UPDATE_APP
        UPDATE_APP = UpdateApplication(self)
        UPDATE_APP.start()
        print "update"
                
    def disableMenu(self):
        #win=Tkinter.Tk()
        #self.grab_set()
        self.menu.entryconfig(1,state=DISABLED)
        self.menu.entryconfig(2,state=DISABLED)
        self.menu.entryconfig(3,state=DISABLED)
        

    def enableMenu(self):
        self.menu.entryconfig(1,state=NORMAL)
        self.menu.entryconfig(2,state=NORMAL)
        self.menu.entryconfig(3,state=NORMAL)
        
        
    
    def cancelUpdateApp(self, event=None):
        global UPDATE_APP
        UPDATE_APP.killUpdate()
        f.quit()
        UPDATE_APP.stop()        
        print 'top'        
        self.tk_cancel.destroy()
        
app = UpdateApplication(None)
try:
    app.killUpdate()
except Exception as exc:
    print exc
root = Tkinter.Tk()
root.resizable(width=Tkinter.FALSE, height=Tkinter.FALSE)
main=SSH(root)
main.start()

root.mainloop()


